4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Input;
14 use Symfony\Component\Console\Exception\RuntimeException;
17 * ArgvInput represents an input coming from the CLI arguments.
21 * $input = new ArgvInput();
23 * By default, the `$_SERVER['argv']` array is used for the input values.
25 * This can be overridden by explicitly passing the input values in the constructor:
27 * $input = new ArgvInput($_SERVER['argv']);
29 * If you pass it yourself, don't forget that the first element of the array
30 * is the name of the running application.
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.
36 * @author Fabien Potencier <fabien@symfony.com>
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
41 class ArgvInput extends Input
46 public function __construct(array $argv = null, InputDefinition $definition = null)
49 $argv = $_SERVER['argv'];
52 // strip the application name
55 $this->tokens = $argv;
57 parent::__construct($definition);
60 protected function setTokens(array $tokens)
62 $this->tokens = $tokens;
68 protected function parse()
71 $this->parsed = $this->tokens;
72 while (null !== $token = array_shift($this->parsed)) {
73 if ($parseOptions && '' == $token) {
74 $this->parseArgument($token);
75 } elseif ($parseOptions && '--' == $token) {
76 $parseOptions = false;
77 } elseif ($parseOptions && 0 === strpos($token, '--')) {
78 $this->parseLongOption($token);
79 } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
80 $this->parseShortOption($token);
82 $this->parseArgument($token);
88 * Parses a short option.
90 private function parseShortOption(string $token)
92 $name = substr($token, 1);
94 if (\strlen($name) > 1) {
95 if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
96 // an option with a value (with no space)
97 $this->addShortOption($name[0], substr($name, 1));
99 $this->parseShortOptionSet($name);
102 $this->addShortOption($name, null);
107 * Parses a short option set.
109 * @throws RuntimeException When option given doesn't exist
111 private function parseShortOptionSet(string $name)
113 $len = \strlen($name);
114 for ($i = 0; $i < $len; ++$i) {
115 if (!$this->definition->hasShortcut($name[$i])) {
116 $encoding = mb_detect_encoding($name, null, true);
117 throw new RuntimeException(sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding)));
120 $option = $this->definition->getOptionForShortcut($name[$i]);
121 if ($option->acceptValue()) {
122 $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
126 $this->addLongOption($option->getName(), null);
132 * Parses a long option.
134 private function parseLongOption(string $token)
136 $name = substr($token, 2);
138 if (false !== $pos = strpos($name, '=')) {
139 if (0 === \strlen($value = substr($name, $pos + 1))) {
140 array_unshift($this->parsed, $value);
142 $this->addLongOption(substr($name, 0, $pos), $value);
144 $this->addLongOption($name, null);
149 * Parses an argument.
151 * @throws RuntimeException When too many arguments are given
153 private function parseArgument(string $token)
155 $c = \count($this->arguments);
157 // if input is expecting another argument, add it
158 if ($this->definition->hasArgument($c)) {
159 $arg = $this->definition->getArgument($c);
160 $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token;
162 // if last argument isArray(), append token to last argument
163 } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
164 $arg = $this->definition->getArgument($c - 1);
165 $this->arguments[$arg->getName()][] = $token;
167 // unexpected argument
169 $all = $this->definition->getArguments();
171 throw new RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
174 throw new RuntimeException(sprintf('No arguments expected, got "%s".', $token));
179 * Adds a short option value.
181 * @throws RuntimeException When option given doesn't exist
183 private function addShortOption(string $shortcut, $value)
185 if (!$this->definition->hasShortcut($shortcut)) {
186 throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
189 $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
193 * Adds a long option value.
195 * @throws RuntimeException When option given doesn't exist
197 private function addLongOption(string $name, $value)
199 if (!$this->definition->hasOption($name)) {
200 throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name));
203 $option = $this->definition->getOption($name);
205 if (null !== $value && !$option->acceptValue()) {
206 throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
209 if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
210 // if option accepts an optional or mandatory argument
211 // let's see if there is one provided
212 $next = array_shift($this->parsed);
213 if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
216 array_unshift($this->parsed, $next);
220 if (null === $value) {
221 if ($option->isValueRequired()) {
222 throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
225 if (!$option->isArray() && !$option->isValueOptional()) {
230 if ($option->isArray()) {
231 $this->options[$name][] = $value;
233 $this->options[$name] = $value;
240 public function getFirstArgument()
243 foreach ($this->tokens as $i => $token) {
244 if ($token && '-' === $token[0]) {
245 if (false !== strpos($token, '=') || !isset($this->tokens[$i + 1])) {
249 // If it's a long option, consider that everything after "--" is the option name.
250 // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator)
251 $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
252 if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
254 } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
275 public function hasParameterOption($values, bool $onlyParams = false)
277 $values = (array) $values;
279 foreach ($this->tokens as $token) {
280 if ($onlyParams && '--' === $token) {
283 foreach ($values as $value) {
284 // Options with values:
285 // For long options, test for '--option=' at beginning
286 // For short options, test for '-o' at beginning
287 $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
288 if ($token === $value || '' !== $leading && 0 === strpos($token, $leading)) {
300 public function getParameterOption($values, $default = false, bool $onlyParams = false)
302 $values = (array) $values;
303 $tokens = $this->tokens;
305 while (0 < \count($tokens)) {
306 $token = array_shift($tokens);
307 if ($onlyParams && '--' === $token) {
311 foreach ($values as $value) {
312 if ($token === $value) {
313 return array_shift($tokens);
315 // Options with values:
316 // For long options, test for '--option=' at beginning
317 // For short options, test for '-o' at beginning
318 $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
319 if ('' !== $leading && 0 === strpos($token, $leading)) {
320 return substr($token, \strlen($leading));
329 * Returns a stringified representation of the args passed to the command.
333 public function __toString()
335 $tokens = array_map(function ($token) {
336 if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
337 return $match[1].$this->escapeToken($match[2]);
340 if ($token && '-' !== $token[0]) {
341 return $this->escapeToken($token);
347 return implode(' ', $tokens);