Bez popisu

StringInput.php 2.6KB

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