Debian Codegraph @

vendor/symfony/console/Input/ArgvInput.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 Symfony\Component\Console\Input;
13
14 use Symfony\Component\Console\Exception\RuntimeException;
15
16 /**
17 * ArgvInput represents an input coming from the CLI arguments.
18 *
19 * Usage:
20 *
21 * $input = new ArgvInput();
22 *
23 * By default, the `$_SERVER['argv']` array is used for the input values.
24 *
25 * This can be overridden by explicitly passing the input values in the constructor:
26 *
27 * $input = new ArgvInput($_SERVER['argv']);
28 *
29 * If you pass it yourself, don't forget that the first element of the array
30 * is the name of the running application.
31 *
32 * When passing an argument to the constructor, be sure that it respects
33 * the same rules as the argv one. It's almost always better to use the
34 * `StringInput` when you want to provide your own input.
35 *
36 * @author Fabien Potencier <[email protected]>
37 *
38 * @see http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
39 * @see http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html#tag_12_02
40 */
41 class ArgvInput extends Input
42 {
43 /** @var list<string> */
44 private array $tokens;
45 private array $parsed;
46
47 /** @param list<string>|null $argv */
48 public function __construct(?array $argv = null, ?InputDefinition $definition = null)
49 {
50 $argv ??= $_SERVER['argv'] ?? [];
51
52 foreach ($argv as $arg) {
53 if (!\is_scalar($arg) && !$arg instanceof \Stringable) {
54 throw new RuntimeException(\sprintf('Argument values expected to be all scalars, got "%s".', get_debug_type($arg)));
55 }
56 }
57
58 // strip the application name
59 array_shift($argv);
60
61 $this->tokens = $argv;
62
63 parent::__construct($definition);
64 }
65
66 /** @param list<string> $tokens */
67 protected function setTokens(array $tokens): void
68 {
69 $this->tokens = $tokens;
70 }
71
72 protected function parse(): void
73 {
74 $parseOptions = true;
75 $this->parsed = $this->tokens;
76 while (null !== $token = array_shift($this->parsed)) {
77 $parseOptions = $this->parseToken($token, $parseOptions);
78 }
79 }
80
81 protected function parseToken(string $token, bool $parseOptions): bool
82 {
83 if ($parseOptions && '' == $token) {
84 $this->parseArgument($token);
85 } elseif ($parseOptions && '--' == $token) {
86 return false;
87 } elseif ($parseOptions && str_starts_with($token, '--')) {
88 $this->parseLongOption($token);
89 } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
90 $this->parseShortOption($token);
91 } else {
92 $this->parseArgument($token);
93 }
94
95 return $parseOptions;
96 }
97
98 /**
99 * Parses a short option.
100 */
101 private function parseShortOption(string $token): void
102 {
103 $name = substr($token, 1);
104
105 if (\strlen($name) > 1) {
106 if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
107 // an option with a value (with no space)
108 $this->addShortOption($name[0], substr($name, 1));
109 } else {
110 $this->parseShortOptionSet($name);
111 }
112 } else {
113 $this->addShortOption($name, null);
114 }
115 }
116
117 /**
118 * Parses a short option set.
119 *
120 * @throws RuntimeException When option given doesn't exist
121 */
122 private function parseShortOptionSet(string $name): void
123 {
124 $len = \strlen($name);
125 for ($i = 0; $i < $len; ++$i) {
126 if (!$this->definition->hasShortcut($name[$i])) {
127 $encoding = mb_detect_encoding($name, null, true);
128 throw new RuntimeException(\sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding)));
129 }
130
131 $option = $this->definition->getOptionForShortcut($name[$i]);
132 if ($option->acceptValue()) {
133 $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
134
135 break;
136 }
137
138 $this->addLongOption($option->getName(), null);
139 }
140 }
141
142 /**
143 * Parses a long option.
144 */
145 private function parseLongOption(string $token): void
146 {
147 $name = substr($token, 2);
148
149 if (false !== $pos = strpos($name, '=')) {
150 if ('' === $value = substr($name, $pos + 1)) {
151 array_unshift($this->parsed, $value);
152 }
153 $this->addLongOption(substr($name, 0, $pos), $value);
154 } else {
155 $this->addLongOption($name, null);
156 }
157 }
158
159 /**
160 * Parses an argument.
161 *
162 * @throws RuntimeException When too many arguments are given
163 */
164 private function parseArgument(string $token): void
165 {
166 $c = \count($this->arguments);
167
168 // if input is expecting another argument, add it
169 if ($this->definition->hasArgument($c)) {
170 $arg = $this->definition->getArgument($c);
171 $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token;
172
173 // if last argument isArray(), append token to last argument
174 } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
175 $arg = $this->definition->getArgument($c - 1);
176 $this->arguments[$arg->getName()][] = $token;
177
178 // unexpected argument
179 } else {
180 $all = $this->definition->getArguments();
181 $symfonyCommandName = null;
182 if (($inputArgument = $all[$key = array_key_first($all) ?? ''] ?? null) && 'command' === $inputArgument->getName()) {
183 $symfonyCommandName = $this->arguments['command'] ?? null;
184 unset($all[$key]);
185 }
186
187 if (\count($all)) {
188 if ($symfonyCommandName) {
189 $message = \sprintf('Too many arguments to "%s" command, expected arguments "%s".', $symfonyCommandName, implode('" "', array_keys($all)));
190 } else {
191 $message = \sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all)));
192 }
193 } elseif ($symfonyCommandName) {
194 $message = \sprintf('No arguments expected for "%s" command, got "%s".', $symfonyCommandName, $token);
195 } else {
196 $message = \sprintf('No arguments expected, got "%s".', $token);
197 }
198
199 throw new RuntimeException($message);
200 }
201 }
202
203 /**
204 * Adds a short option value.
205 *
206 * @throws RuntimeException When option given doesn't exist
207 */
208 private function addShortOption(string $shortcut, mixed $value): void
209 {
210 if (!$this->definition->hasShortcut($shortcut)) {
211 throw new RuntimeException(\sprintf('The "-%s" option does not exist.', $shortcut));
212 }
213
214 $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
215 }
216
217 /**
218 * Adds a long option value.
219 *
220 * @throws RuntimeException When option given doesn't exist
221 */
222 private function addLongOption(string $name, mixed $value): void
223 {
224 if (!$this->definition->hasOption($name)) {
225 if (!$this->definition->hasNegation($name)) {
226 throw new RuntimeException(\sprintf('The "--%s" option does not exist.', $name));
227 }
228
229 $optionName = $this->definition->negationToName($name);
230 if (null !== $value) {
231 throw new RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
232 }
233 $this->options[$optionName] = false;
234
235 return;
236 }
237
238 $option = $this->definition->getOption($name);
239
240 if (null !== $value && !$option->acceptValue()) {
241 throw new RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
242 }
243
244 if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
245 // if option accepts an optional or mandatory argument
246 // let's see if there is one provided
247 $next = array_shift($this->parsed);
248 if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
249 $value = $next;
250 } else {
251 array_unshift($this->parsed, $next);
252 }
253 }
254
255 if (null === $value) {
256 if ($option->isValueRequired()) {
257 throw new RuntimeException(\sprintf('The "--%s" option requires a value.', $name));
258 }
259
260 if (!$option->isArray() && !$option->isValueOptional()) {
261 $value = true;
262 }
263 }
264
265 if ($option->isArray()) {
266 $this->options[$name][] = $value;
267 } else {
268 $this->options[$name] = $value;
269 }
270 }
271
272 public function getFirstArgument(): ?string
273 {
274 $isOption = false;
275 foreach ($this->tokens as $i => $token) {
276 if ($token && '-' === $token[0]) {
277 if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) {
278 continue;
279 }
280
281 // If it's a long option, consider that everything after "--" is the option name.
282 // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator)
283 $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
284 if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
285 // noop
286 } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
287 $isOption = true;
288 }
289
290 continue;
291 }
292
293 if ($isOption) {
294 $isOption = false;
295 continue;
296 }
297
298 return $token;
299 }
300
301 return null;
302 }
303
304 public function hasParameterOption(string|array $values, bool $onlyParams = false): bool
305 {
306 $values = (array) $values;
307
308 foreach ($this->tokens as $token) {
309 if ($onlyParams && '--' === $token) {
310 return false;
311 }
312 foreach ($values as $value) {
313 // Options with values:
314 // For long options, test for '--option=' at beginning
315 // For short options, test for '-o' at beginning
316 $leading = str_starts_with($value, '--') ? $value.'=' : $value;
317 if ($token === $value || '' !== $leading && str_starts_with($token, $leading)) {
318 return true;
319 }
320 }
321 }
322
323 return false;
324 }
325
326 public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed
327 {
328 $values = (array) $values;
329 $tokens = $this->tokens;
330
331 while (0 < \count($tokens)) {
332 $token = array_shift($tokens);
333 if ($onlyParams && '--' === $token) {
334 return $default;
335 }
336
337 foreach ($values as $value) {
338 if ($token === $value) {
339 return array_shift($tokens);
340 }
341 // Options with values:
342 // For long options, test for '--option=' at beginning
343 // For short options, test for '-o' at beginning
344 $leading = str_starts_with($value, '--') ? $value.'=' : $value;
345 if ('' !== $leading && str_starts_with($token, $leading)) {
346 return substr($token, \strlen($leading));
347 }
348 }
349 }
350
351 return $default;
352 }
353
354 /**
355 * Returns un-parsed and not validated tokens.
356 *
357 * @param bool $strip Whether to return the raw parameters (false) or the values after the command name (true)
358 *
359 * @return list<string>
360 */
361 public function getRawTokens(bool $strip = false): array
362 {
363 if (!$strip) {
364 return $this->tokens;
365 }
366
367 $parameters = [];
368 $keep = false;
369 foreach ($this->tokens as $value) {
370 if (!$keep && $value === $this->getFirstArgument()) {
371 $keep = true;
372
373 continue;
374 }
375 if ($keep) {
376 $parameters[] = $value;
377 }
378 }
379
380 return $parameters;
381 }
382
383 /**
384 * Returns a stringified representation of the args passed to the command.
385 */
386 public function __toString(): string
387 {
388 $tokens = array_map(function ($token) {
389 if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
390 return $match[1].$this->escapeToken($match[2]);
391 }
392
393 if ($token && '-' !== $token[0]) {
394 return $this->escapeToken($token);
395 }
396
397 return $token;
398 }, $this->tokens);
399
400 return implode(' ', $tokens);
401 }
402 }