68a4252a2205dbef059293b19aee59ae0e5fe0be
[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             return;
169         }
170
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;
175
176             return;
177         }
178
179         // unexpected argument
180         $all = $this->definition->getArguments();
181         if (count($all)) {
182             throw new \RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
183         }
184
185         throw new \RuntimeException(sprintf('No arguments expected, got "%s".', $token));
186     }
187
188     // Everything below this is copypasta from ArgvInput private methods
189
190     /**
191      * Parses a short option.
192      *
193      * @param string $token The current token
194      */
195     private function parseShortOption($token)
196     {
197         $name = substr($token, 1);
198
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));
203             } else {
204                 $this->parseShortOptionSet($name);
205             }
206         } else {
207             $this->addShortOption($name, null);
208         }
209     }
210
211     /**
212      * Parses a short option set.
213      *
214      * @param string $name The current token
215      *
216      * @throws \RuntimeException When option given doesn't exist
217      */
218     private function parseShortOptionSet($name)
219     {
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]));
224             }
225
226             $option = $this->definition->getOptionForShortcut($name[$i]);
227             if ($option->acceptValue()) {
228                 $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
229
230                 break;
231             } else {
232                 $this->addLongOption($option->getName(), null);
233             }
234         }
235     }
236
237     /**
238      * Parses a long option.
239      *
240      * @param string $token The current token
241      */
242     private function parseLongOption($token)
243     {
244         $name = substr($token, 2);
245
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) {
251                     $value = '';
252                 }
253                 array_unshift($this->parsed, array($value, null));
254             }
255             $this->addLongOption(substr($name, 0, $pos), $value);
256         } else {
257             $this->addLongOption($name, null);
258         }
259     }
260
261     /**
262      * Adds a short option value.
263      *
264      * @param string $shortcut The short option key
265      * @param mixed  $value    The value for the option
266      *
267      * @throws \RuntimeException When option given doesn't exist
268      */
269     private function addShortOption($shortcut, $value)
270     {
271         if (!$this->definition->hasShortcut($shortcut)) {
272             throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
273         }
274
275         $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
276     }
277
278     /**
279      * Adds a long option value.
280      *
281      * @param string $name  The long option key
282      * @param mixed  $value The value for the option
283      *
284      * @throws \RuntimeException When option given doesn't exist
285      */
286     private function addLongOption($name, $value)
287     {
288         if (!$this->definition->hasOption($name)) {
289             throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
290         }
291
292         $option = $this->definition->getOption($name);
293
294         if (null !== $value && !$option->acceptValue()) {
295             throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
296         }
297
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)) {
304                 $value = $nextToken;
305             } else {
306                 array_unshift($this->parsed, $next);
307             }
308         }
309
310         if (null === $value) {
311             if ($option->isValueRequired()) {
312                 throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
313             }
314
315             if (!$option->isArray() && !$option->isValueOptional()) {
316                 $value = true;
317             }
318         }
319
320         if ($option->isArray()) {
321             $this->options[$name][] = $value;
322         } else {
323             $this->options[$name] = $value;
324         }
325     }
326 }