ArgvInput.php 12 KB

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