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;
14 use Symfony\Component\Console\Exception\InvalidArgumentException;
17 * StringInput represents an input provided as a string.
21 * $input = new StringInput('foo --bar="foobar"');
23 * @author Fabien Potencier <fabien@symfony.com>
25 class StringInput extends ArgvInput
27 const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
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
36 * @deprecated The second argument is deprecated as it does not work (will be removed in 3.0), use 'bind' method instead
38 public function __construct($input, InputDefinition $definition = null)
41 @trigger_error('The $definition argument of the '.__METHOD__.' method is deprecated and will be removed in 3.0. Set this parameter with the bind() method instead.', E_USER_DEPRECATED);
44 parent::__construct(array(), null);
46 $this->setTokens($this->tokenize($input));
48 if (null !== $definition) {
49 $this->bind($definition);
56 * @param string $input The input to tokenize
58 * @return array An array of tokens
60 * @throws InvalidArgumentException When unable to parse input (should never happen)
62 private function tokenize($input)
65 $length = strlen($input);
67 while ($cursor < $length) {
68 if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
69 } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
70 $tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
71 } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
72 $tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
73 } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
74 $tokens[] = stripcslashes($match[1]);
76 // should never happen
77 throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
80 $cursor += strlen($match[0]);