4 * This file is part of Psy Shell.
6 * (c) 2012-2017 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
14 use Symfony\Component\Console\Input\InputDefinition;
15 use Symfony\Component\Console\Input\StringInput;
18 * A StringInput subclass specialized for code arguments.
20 class ShellInput extends StringInput
22 private $hasCodeArgument = false;
25 * Unlike the parent implementation's tokens, this contains an array of
26 * token/rest pairs, so that code arguments can be handled while parsing.
34 * @param string $input An array of parameters from the CLI (in the argv format)
36 public function __construct($input)
38 parent::__construct($input);
40 $this->tokenPairs = $this->tokenize($input);
46 * @throws \InvalidArgumentException if $definition has CodeArgument before the final argument position
48 public function bind(InputDefinition $definition)
50 $hasCodeArgument = false;
52 if ($definition->getArgumentCount() > 0) {
53 $args = $definition->getArguments();
54 $lastArg = array_pop($args);
55 foreach ($args as $arg) {
56 if ($arg instanceof CodeArgument) {
57 $msg = sprintf('Unexpected CodeArgument before the final position: %s', $arg->getName());
58 throw new \InvalidArgumentException($msg);
62 if ($lastArg instanceof CodeArgument) {
63 $hasCodeArgument = true;
67 $this->hasCodeArgument = $hasCodeArgument;
69 return parent::bind($definition);
75 * The version of this on StringInput is good, but doesn't handle code
76 * arguments if they're at all complicated. This does :)
78 * @param string $input The input to tokenize
80 * @return array An array of token/rest pairs
82 * @throws \InvalidArgumentException When unable to parse input (should never happen)
84 private function tokenize($input)
87 $length = strlen($input);
89 while ($cursor < $length) {
90 if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
91 } elseif (preg_match('/([^="\'\s]+?)(=?)(' . StringInput::REGEX_QUOTED_STRING . '+)/A', $input, $match, null, $cursor)) {
93 $match[1] . $match[2] . stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2))),
94 substr($input, $cursor),
96 } elseif (preg_match('/' . StringInput::REGEX_QUOTED_STRING . '/A', $input, $match, null, $cursor)) {
98 stripcslashes(substr($match[0], 1, strlen($match[0]) - 2)),
99 substr($input, $cursor),
101 } elseif (preg_match('/' . StringInput::REGEX_STRING . '/A', $input, $match, null, $cursor)) {
103 stripcslashes($match[1]),
104 substr($input, $cursor),
107 // should never happen
108 throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
111 $cursor += strlen($match[0]);
118 * Same as parent, but with some bonus handling for code arguments.
120 protected function parse()
122 $parseOptions = true;
123 $this->parsed = $this->tokenPairs;
124 while (null !== $tokenPair = array_shift($this->parsed)) {
125 // token is what you'd expect. rest is the remainder of the input
126 // string, including token, and will be used if this is a code arg.
127 list($token, $rest) = $tokenPair;
129 if ($parseOptions && '' === $token) {
130 $this->parseShellArgument($token, $rest);
131 } elseif ($parseOptions && '--' === $token) {
132 $parseOptions = false;
133 } elseif ($parseOptions && 0 === strpos($token, '--')) {
134 $this->parseLongOption($token);
135 } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
136 $this->parseShortOption($token);
138 $this->parseShellArgument($token, $rest);
144 * Parses an argument, with bonus handling for code arguments.
146 * @param string $token The current token
147 * @param string $rest The remaining unparsed input, including the current token
149 * @throws \RuntimeException When too many arguments are given
151 private function parseShellArgument($token, $rest)
153 $c = count($this->arguments);
155 // if input is expecting another argument, add it
156 if ($this->definition->hasArgument($c)) {
157 $arg = $this->definition->getArgument($c);
159 if ($arg instanceof CodeArgument) {
160 // When we find a code argument, we're done parsing. Add the
161 // remaining input to the current argument and call it a day.
162 $this->parsed = array();
163 $this->arguments[$arg->getName()] = $rest;
165 $this->arguments[$arg->getName()] = $arg->isArray() ? array($token) : $token;
171 // if last argument isArray(), append token to last argument
172 if ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
173 $arg = $this->definition->getArgument($c - 1);
174 $this->arguments[$arg->getName()][] = $token;
179 // unexpected argument
180 $all = $this->definition->getArguments();
182 throw new \RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
185 throw new \RuntimeException(sprintf('No arguments expected, got "%s".', $token));
188 // Everything below this is copypasta from ArgvInput private methods
191 * Parses a short option.
193 * @param string $token The current token
195 private function parseShortOption($token)
197 $name = substr($token, 1);
199 if (strlen($name) > 1) {
200 if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
201 // an option with a value (with no space)
202 $this->addShortOption($name[0], substr($name, 1));
204 $this->parseShortOptionSet($name);
207 $this->addShortOption($name, null);
212 * Parses a short option set.
214 * @param string $name The current token
216 * @throws \RuntimeException When option given doesn't exist
218 private function parseShortOptionSet($name)
220 $len = strlen($name);
221 for ($i = 0; $i < $len; $i++) {
222 if (!$this->definition->hasShortcut($name[$i])) {
223 throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
226 $option = $this->definition->getOptionForShortcut($name[$i]);
227 if ($option->acceptValue()) {
228 $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
232 $this->addLongOption($option->getName(), null);
238 * Parses a long option.
240 * @param string $token The current token
242 private function parseLongOption($token)
244 $name = substr($token, 2);
246 if (false !== $pos = strpos($name, '=')) {
247 if (0 === strlen($value = substr($name, $pos + 1))) {
248 // if no value after "=" then substr() returns "" since php7 only, false before
249 // see http://php.net/manual/fr/migration70.incompatible.php#119151
250 if (PHP_VERSION_ID < 70000 && false === $value) {
253 array_unshift($this->parsed, array($value, null));
255 $this->addLongOption(substr($name, 0, $pos), $value);
257 $this->addLongOption($name, null);
262 * Adds a short option value.
264 * @param string $shortcut The short option key
265 * @param mixed $value The value for the option
267 * @throws \RuntimeException When option given doesn't exist
269 private function addShortOption($shortcut, $value)
271 if (!$this->definition->hasShortcut($shortcut)) {
272 throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
275 $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
279 * Adds a long option value.
281 * @param string $name The long option key
282 * @param mixed $value The value for the option
284 * @throws \RuntimeException When option given doesn't exist
286 private function addLongOption($name, $value)
288 if (!$this->definition->hasOption($name)) {
289 throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
292 $option = $this->definition->getOption($name);
294 if (null !== $value && !$option->acceptValue()) {
295 throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
298 if (in_array($value, array('', null), true) && $option->acceptValue() && count($this->parsed)) {
299 // if option accepts an optional or mandatory argument
300 // let's see if there is one provided
301 $next = array_shift($this->parsed);
302 $nextToken = $next[0];
303 if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || in_array($nextToken, array('', null), true)) {
306 array_unshift($this->parsed, $next);
310 if (null === $value) {
311 if ($option->isValueRequired()) {
312 throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
315 if (!$option->isArray() && !$option->isValueOptional()) {
320 if ($option->isArray()) {
321 $this->options[$name][] = $value;
323 $this->options[$name] = $value;