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;
168 // if last argument isArray(), append token to last argument
169 } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
170 $arg = $this->definition->getArgument($c - 1);
171 $this->arguments[$arg->getName()][] = $token;
173 // unexpected argument
175 $all = $this->definition->getArguments();
177 throw new \RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
180 throw new \RuntimeException(sprintf('No arguments expected, got "%s".', $token));
184 // Everything below this is copypasta from ArgvInput private methods
187 * Parses a short option.
189 * @param string $token The current token
191 private function parseShortOption($token)
193 $name = substr($token, 1);
195 if (strlen($name) > 1) {
196 if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
197 // an option with a value (with no space)
198 $this->addShortOption($name[0], substr($name, 1));
200 $this->parseShortOptionSet($name);
203 $this->addShortOption($name, null);
208 * Parses a short option set.
210 * @param string $name The current token
212 * @throws \RuntimeException When option given doesn't exist
214 private function parseShortOptionSet($name)
216 $len = strlen($name);
217 for ($i = 0; $i < $len; ++$i) {
218 if (!$this->definition->hasShortcut($name[$i])) {
219 throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
222 $option = $this->definition->getOptionForShortcut($name[$i]);
223 if ($option->acceptValue()) {
224 $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
228 $this->addLongOption($option->getName(), null);
234 * Parses a long option.
236 * @param string $token The current token
238 private function parseLongOption($token)
240 $name = substr($token, 2);
242 if (false !== $pos = strpos($name, '=')) {
243 if (0 === strlen($value = substr($name, $pos + 1))) {
244 // if no value after "=" then substr() returns "" since php7 only, false before
245 // see http://php.net/manual/fr/migration70.incompatible.php#119151
246 if (PHP_VERSION_ID < 70000 && false === $value) {
249 array_unshift($this->parsed, array($value, null));
251 $this->addLongOption(substr($name, 0, $pos), $value);
253 $this->addLongOption($name, null);
258 * Adds a short option value.
260 * @param string $shortcut The short option key
261 * @param mixed $value The value for the option
263 * @throws \RuntimeException When option given doesn't exist
265 private function addShortOption($shortcut, $value)
267 if (!$this->definition->hasShortcut($shortcut)) {
268 throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
271 $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
275 * Adds a long option value.
277 * @param string $name The long option key
278 * @param mixed $value The value for the option
280 * @throws \RuntimeException When option given doesn't exist
282 private function addLongOption($name, $value)
284 if (!$this->definition->hasOption($name)) {
285 throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
288 $option = $this->definition->getOption($name);
290 if (null !== $value && !$option->acceptValue()) {
291 throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
294 if (in_array($value, array('', null), true) && $option->acceptValue() && count($this->parsed)) {
295 // if option accepts an optional or mandatory argument
296 // let's see if there is one provided
297 $next = array_shift($this->parsed);
298 $nextToken = $next[0];
299 if ((isset($nextToken[0]) && '-' !== $nextToken[0]) || in_array($nextToken, array('', null), true)) {
302 array_unshift($this->parsed, $next);
306 if (null === $value) {
307 if ($option->isValueRequired()) {
308 throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
311 if (!$option->isArray() && !$option->isValueOptional()) {
316 if ($option->isArray()) {
317 $this->options[$name][] = $value;
319 $this->options[$name] = $value;