StringInput.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. /**
  24. * @deprecated since Symfony 6.1
  25. */
  26. public const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
  27. public const REGEX_UNQUOTED_STRING = '([^\s\\\\]+?)';
  28. public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
  29. /**
  30. * @param string $input A string representing the parameters from the CLI
  31. */
  32. public function __construct($input)
  33. {
  34. parent::__construct([]);
  35. $this->setTokens($this->tokenize($input));
  36. }
  37. /**
  38. * Tokenizes a string.
  39. *
  40. * @throws InvalidArgumentException When unable to parse input (should never happen)
  41. * @param string $input
  42. */
  43. private function tokenize($input)
  44. {
  45. $tokens = [];
  46. $length = \strlen($input);
  47. $cursor = 0;
  48. $token = null;
  49. while ($cursor < $length) {
  50. if ('\\' === $input[$cursor]) {
  51. $token .= $input[++$cursor] ?? '';
  52. ++$cursor;
  53. continue;
  54. }
  55. if (preg_match('/\s+/A', $input, $match, 0, $cursor)) {
  56. if (null !== $token) {
  57. $tokens[] = $token;
  58. $token = null;
  59. }
  60. } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) {
  61. $token .= $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, -1)));
  62. } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
  63. $token .= stripcslashes(substr($match[0], 1, -1));
  64. } elseif (preg_match('/'.self::REGEX_UNQUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
  65. $token .= $match[1];
  66. } else {
  67. // should never happen
  68. throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10)));
  69. }
  70. $cursor += \strlen($match[0]);
  71. }
  72. if (null !== $token) {
  73. $tokens[] = $token;
  74. }
  75. return $tokens;
  76. }
  77. }