Yaffs site version 1.1
[yaffs-website] / vendor / psy / psysh / src / Psy / Input / ShellInput.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2017 Justin Hileman
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Psy\Input;
13
14 use Symfony\Component\Console\Input\InputDefinition;
15 use Symfony\Component\Console\Input\StringInput;
16
17 /**
18  * A StringInput subclass specialized for code arguments.
19  */
20 class ShellInput extends StringInput
21 {
22     private $hasCodeArgument = false;
23
24     /**
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.
27      */
28     private $tokenPairs;
29     private $parsed;
30
31     /**
32      * Constructor.
33      *
34      * @param string $input An array of parameters from the CLI (in the argv format)
35      */
36     public function __construct($input)
37     {
38         parent::__construct($input);
39
40         $this->tokenPairs = $this->tokenize($input);
41     }
42
43     /**
44      * {@inheritdoc}
45      *
46      * @throws \InvalidArgumentException if $definition has CodeArgument before the final argument position
47      */
48     public function bind(InputDefinition $definition)
49     {
50         $hasCodeArgument = false;
51
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);
59                 }
60             }
61
62             if ($lastArg instanceof CodeArgument) {
63                 $hasCodeArgument = true;
64             }
65         }
66
67         $this->hasCodeArgument = $hasCodeArgument;
68
69         return parent::bind($definition);
70     }
71
72     /**
73      * Tokenizes a string.
74      *
75      * The version of this on StringInput is good, but doesn't handle code
76      * arguments if they're at all complicated. This does :)
77      *
78      * @param string $input The input to tokenize
79      *
80      * @return array An array of token/rest pairs
81      *
82      * @throws \InvalidArgumentException When unable to parse input (should never happen)
83      */
84     private function tokenize($input)
85     {
86         $tokens = array();
87         $length = strlen($input);
88         $cursor = 0;
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)) {
92                 $tokens[] = array(
93                     $match[1] . $match[2] . stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2))),
94                     substr($input, $cursor),
95                 );
96             } elseif (preg_match('/' . StringInput::REGEX_QUOTED_STRING . '/A', $input, $match, null, $cursor)) {
97                 $tokens[] = array(
98                     stripcslashes(substr($match[0], 1, strlen($match[0]) - 2)),
99                     substr($input, $cursor),
100                 );
101             } elseif (preg_match('/' . StringInput::REGEX_STRING . '/A', $input, $match, null, $cursor)) {
102                 $tokens[] = array(
103                     stripcslashes($match[1]),
104                     substr($input, $cursor),
105                 );
106             } else {
107                 // should never happen
108                 throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
109             }
110
111             $cursor += strlen($match[0]);
112         }
113
114         return $tokens;
115     }
116
117     /**
118      * Same as parent, but with some bonus handling for code arguments.
119      */
120     protected function parse()
121     {
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;
128
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);
137             } else {
138                 $this->parseShellArgument($token, $rest);
139             }
140         }
141     }
142
143     /**
144      * Parses an argument, with bonus handling for code arguments.
145      *
146      * @param string $token The current token
147      * @param string $rest  The remaining unparsed input, including the current token
148      *
149      * @throws \RuntimeException When too many arguments are given
150      */
151     private function parseShellArgument($token, $rest)
152     {
153         $c = count($this->arguments);
154
155         // if input is expecting another argument, add it
156         if ($this->definition->hasArgument($c)) {
157             $arg = $this->definition->getArgument($c);
158
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;
164             } else {
165                 $this->arguments[$arg->getName()] = $arg->isArray() ? array($token) : $token;
166             }
167
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;
172
173         // unexpected argument
174         } else {
175             $all = $this->definition->getArguments();
176             if (count($all)) {
177                 throw new \RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
178             }
179
180             throw new \RuntimeException(sprintf('No arguments expected, got "%s".', $token));
181         }
182     }
183
184     // Everything below this is copypasta from ArgvInput private methods
185
186     /**
187      * Parses a short option.
188      *
189      * @param string $token The current token
190      */
191     private function parseShortOption($token)
192     {
193         $name = substr($token, 1);
194
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));
199             } else {
200                 $this->parseShortOptionSet($name);
201             }
202         } else {
203             $this->addShortOption($name, null);
204         }
205     }
206
207     /**
208      * Parses a short option set.
209      *
210      * @param string $name The current token
211      *
212      * @throws \RuntimeException When option given doesn't exist
213      */
214     private function parseShortOptionSet($name)
215     {
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]));
220             }
221
222             $option = $this->definition->getOptionForShortcut($name[$i]);
223             if ($option->acceptValue()) {
224                 $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
225
226                 break;
227             } else {
228                 $this->addLongOption($option->getName(), null);
229             }
230         }
231     }
232
233     /**
234      * Parses a long option.
235      *
236      * @param string $token The current token
237      */
238     private function parseLongOption($token)
239     {
240         $name = substr($token, 2);
241
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) {
247                     $value = '';
248                 }
249                 array_unshift($this->parsed, array($value, null));
250             }
251             $this->addLongOption(substr($name, 0, $pos), $value);
252         } else {
253             $this->addLongOption($name, null);
254         }
255     }
256
257     /**
258      * Adds a short option value.
259      *
260      * @param string $shortcut The short option key
261      * @param mixed  $value    The value for the option
262      *
263      * @throws \RuntimeException When option given doesn't exist
264      */
265     private function addShortOption($shortcut, $value)
266     {
267         if (!$this->definition->hasShortcut($shortcut)) {
268             throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
269         }
270
271         $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
272     }
273
274     /**
275      * Adds a long option value.
276      *
277      * @param string $name  The long option key
278      * @param mixed  $value The value for the option
279      *
280      * @throws \RuntimeException When option given doesn't exist
281      */
282     private function addLongOption($name, $value)
283     {
284         if (!$this->definition->hasOption($name)) {
285             throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
286         }
287
288         $option = $this->definition->getOption($name);
289
290         if (null !== $value && !$option->acceptValue()) {
291             throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
292         }
293
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)) {
300                 $value = $nextToken;
301             } else {
302                 array_unshift($this->parsed, $next);
303             }
304         }
305
306         if (null === $value) {
307             if ($option->isValueRequired()) {
308                 throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
309             }
310
311             if (!$option->isArray() && !$option->isValueOptional()) {
312                 $value = true;
313             }
314         }
315
316         if ($option->isArray()) {
317             $this->options[$name][] = $value;
318         } else {
319             $this->options[$name] = $value;
320         }
321     }
322 }