StringInput.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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_UNQUOTED_STRING = '([^\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. * @return list<string>
  37. *
  38. * @throws InvalidArgumentException When unable to parse input (should never happen)
  39. */
  40. private function tokenize(string $input): array
  41. {
  42. $tokens = [];
  43. $length = \strlen($input);
  44. $cursor = 0;
  45. $token = null;
  46. while ($cursor < $length) {
  47. if ('\\' === $input[$cursor]) {
  48. $token .= $input[++$cursor] ?? '';
  49. ++$cursor;
  50. continue;
  51. }
  52. if (preg_match('/\s+/A', $input, $match, 0, $cursor)) {
  53. if (null !== $token) {
  54. $tokens[] = $token;
  55. $token = null;
  56. }
  57. } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) {
  58. $token .= $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, -1)));
  59. } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
  60. $token .= stripcslashes(substr($match[0], 1, -1));
  61. } elseif (preg_match('/'.self::REGEX_UNQUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
  62. $token .= $match[1];
  63. } else {
  64. // should never happen
  65. throw new InvalidArgumentException(\sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10)));
  66. }
  67. $cursor += \strlen($match[0]);
  68. }
  69. if (null !== $token) {
  70. $tokens[] = $token;
  71. }
  72. return $tokens;
  73. }
  74. }