StringInput.php 2.4 KB

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