StringInput.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  12. * StringInput represents an input provided as a string.
  13. *
  14. * Usage:
  15. *
  16. * $input = new StringInput('foo --bar="foobar"');
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. *
  20. * @api
  21. */
  22. class StringInput extends ArgvInput
  23. {
  24. const REGEX_STRING = '([^ ]+?)(?: |(?<!\\\\)"|(?<!\\\\)\'|$)';
  25. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
  26. /**
  27. * Constructor.
  28. *
  29. * @param string $input An array of parameters from the CLI (in the argv format)
  30. * @param InputDefinition $definition A InputDefinition instance
  31. *
  32. * @api
  33. */
  34. public function __construct($input, InputDefinition $definition = null)
  35. {
  36. parent::__construct(array(), $definition);
  37. $this->setTokens($this->tokenize($input));
  38. }
  39. /**
  40. * Tokenizes a string.
  41. *
  42. * @param string $input The input to tokenize
  43. *
  44. * @throws \InvalidArgumentException When unable to parse input (should never happen)
  45. */
  46. private function tokenize($input)
  47. {
  48. $input = preg_replace('/(\r\n|\r|\n|\t)/', ' ', $input);
  49. $tokens = array();
  50. $length = strlen($input);
  51. $cursor = 0;
  52. while ($cursor < $length) {
  53. if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
  54. } elseif (preg_match('/([^="\' ]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
  55. $tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
  56. } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
  57. $tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
  58. } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
  59. $tokens[] = stripcslashes($match[1]);
  60. } else {
  61. // should never happen
  62. // @codeCoverageIgnoreStart
  63. throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
  64. // @codeCoverageIgnoreEnd
  65. }
  66. $cursor += strlen($match[0]);
  67. }
  68. return $tokens;
  69. }
  70. }