4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Input;
15 * StringInput represents an input provided as a string.
19 * $input = new StringInput('foo --bar="foobar"');
21 * @author Fabien Potencier <fabien@symfony.com>
25 class StringInput extends ArgvInput
27 const REGEX_STRING = '([^ ]+?)(?: |(?<!\\\\)"|(?<!\\\\)\'|$)';
28 const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
33 * @param string $input An array of parameters from the CLI (in the argv format)
34 * @param InputDefinition $definition A InputDefinition instance
38 public function __construct($input, InputDefinition $definition = null)
40 parent::__construct(array(), $definition);
42 $this->setTokens($this->tokenize($input));
48 * @param string $input The input to tokenize
50 * @return array An array of tokens
52 * @throws \InvalidArgumentException When unable to parse input (should never happen)
54 private function tokenize($input)
56 $input = preg_replace('/(\r\n|\r|\n|\t)/', ' ', $input);
59 $length = strlen($input);
61 while ($cursor < $length) {
62 if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
63 } elseif (preg_match('/([^="\' ]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
64 $tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
65 } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
66 $tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
67 } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
68 $tokens[] = stripcslashes($match[1]);
70 // should never happen
71 // @codeCoverageIgnoreStart
72 throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
73 // @codeCoverageIgnoreEnd
76 $cursor += strlen($match[0]);