StringInput.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
  24. 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(array());
  31. $this->setTokens($this->tokenize($input));
  32. }
  33. /**
  34. * Tokenizes a string.
  35. *
  36. * @param string $input The input to tokenize
  37. *
  38. * @return array An array of tokens
  39. *
  40. * @throws InvalidArgumentException When unable to parse input (should never happen)
  41. */
  42. private function tokenize($input)
  43. {
  44. $tokens = array();
  45. $length = strlen($input);
  46. $cursor = 0;
  47. while ($cursor < $length) {
  48. if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
  49. } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
  50. $tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
  51. } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
  52. $tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
  53. } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
  54. $tokens[] = stripcslashes($match[1]);
  55. } else {
  56. // should never happen
  57. throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
  58. }
  59. $cursor += strlen($match[0]);
  60. }
  61. return $tokens;
  62. }
  63. }