You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.2 KiB

3 years ago
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Input;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. /**
  13. * StringInput represents an input provided as a string.
  14. *
  15. * Usage:
  16. *
  17. * $input = new StringInput('foo --bar="foobar"');
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class StringInput extends ArgvInput
  22. {
  23. public const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
  24. public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
  25. /**
  26. * @param string $input A string representing the parameters from the CLI
  27. */
  28. public function __construct(string $input)
  29. {
  30. parent::__construct([]);
  31. $this->setTokens($this->tokenize($input));
  32. }
  33. /**
  34. * Tokenizes a string.
  35. *
  36. * @throws InvalidArgumentException When unable to parse input (should never happen)
  37. */
  38. private function tokenize(string $input): array
  39. {
  40. $tokens = [];
  41. $length = \strlen($input);
  42. $cursor = 0;
  43. while ($cursor < $length) {
  44. if (preg_match('/\s+/A', $input, $match, 0, $cursor)) {
  45. } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) {
  46. $tokens[] = $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, \strlen($match[3]) - 2)));
  47. } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
  48. $tokens[] = stripcslashes(substr($match[0], 1, \strlen($match[0]) - 2));
  49. } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, 0, $cursor)) {
  50. $tokens[] = stripcslashes($match[1]);
  51. } else {
  52. // should never happen
  53. throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10)));
  54. }
  55. $cursor += \strlen($match[0]);
  56. }
  57. return $tokens;
  58. }
  59. }