ArgvInput.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. /** @var list<string> */
  40. private array $tokens;
  41. private array $parsed;
  42. /** @param list<string>|null $argv */
  43. public function __construct(?array $argv = null, ?InputDefinition $definition = null)
  44. {
  45. $argv ??= $_SERVER['argv'] ?? [];
  46. foreach ($argv as $arg) {
  47. if (!\is_scalar($arg) && !$arg instanceof \Stringable) {
  48. throw new RuntimeException(\sprintf('Argument values expected to be all scalars, got "%s".', get_debug_type($arg)));
  49. }
  50. }
  51. // strip the application name
  52. array_shift($argv);
  53. $this->tokens = $argv;
  54. parent::__construct($definition);
  55. }
  56. /** @param list<string> $tokens */
  57. protected function setTokens(array $tokens): void
  58. {
  59. $this->tokens = $tokens;
  60. }
  61. protected function parse(): void
  62. {
  63. $parseOptions = true;
  64. $this->parsed = $this->tokens;
  65. while (null !== $token = array_shift($this->parsed)) {
  66. $parseOptions = $this->parseToken($token, $parseOptions);
  67. }
  68. }
  69. protected function parseToken(string $token, bool $parseOptions): bool
  70. {
  71. if ($parseOptions && '' == $token) {
  72. $this->parseArgument($token);
  73. } elseif ($parseOptions && '--' == $token) {
  74. return false;
  75. } elseif ($parseOptions && str_starts_with($token, '--')) {
  76. $this->parseLongOption($token);
  77. } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
  78. $this->parseShortOption($token);
  79. } else {
  80. $this->parseArgument($token);
  81. }
  82. return $parseOptions;
  83. }
  84. /**
  85. * Parses a short option.
  86. */
  87. private function parseShortOption(string $token): void
  88. {
  89. $name = substr($token, 1);
  90. if (\strlen($name) > 1) {
  91. if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
  92. // an option with a value (with no space)
  93. $this->addShortOption($name[0], substr($name, 1));
  94. } else {
  95. $this->parseShortOptionSet($name);
  96. }
  97. } else {
  98. $this->addShortOption($name, null);
  99. }
  100. }
  101. /**
  102. * Parses a short option set.
  103. *
  104. * @throws RuntimeException When option given doesn't exist
  105. */
  106. private function parseShortOptionSet(string $name): void
  107. {
  108. $len = \strlen($name);
  109. for ($i = 0; $i < $len; ++$i) {
  110. if (!$this->definition->hasShortcut($name[$i])) {
  111. $encoding = mb_detect_encoding($name, null, true);
  112. throw new RuntimeException(\sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding)));
  113. }
  114. $option = $this->definition->getOptionForShortcut($name[$i]);
  115. if ($option->acceptValue()) {
  116. $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
  117. break;
  118. }
  119. $this->addLongOption($option->getName(), null);
  120. }
  121. }
  122. /**
  123. * Parses a long option.
  124. */
  125. private function parseLongOption(string $token): void
  126. {
  127. $name = substr($token, 2);
  128. if (false !== $pos = strpos($name, '=')) {
  129. if ('' === $value = substr($name, $pos + 1)) {
  130. array_unshift($this->parsed, $value);
  131. }
  132. $this->addLongOption(substr($name, 0, $pos), $value);
  133. } else {
  134. $this->addLongOption($name, null);
  135. }
  136. }
  137. /**
  138. * Parses an argument.
  139. *
  140. * @throws RuntimeException When too many arguments are given
  141. */
  142. private function parseArgument(string $token): void
  143. {
  144. $c = \count($this->arguments);
  145. // if input is expecting another argument, add it
  146. if ($this->definition->hasArgument($c)) {
  147. $arg = $this->definition->getArgument($c);
  148. $this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token;
  149. // if last argument isArray(), append token to last argument
  150. } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
  151. $arg = $this->definition->getArgument($c - 1);
  152. $this->arguments[$arg->getName()][] = $token;
  153. // unexpected argument
  154. } else {
  155. $all = $this->definition->getArguments();
  156. $symfonyCommandName = null;
  157. if (($inputArgument = $all[$key = array_key_first($all) ?? ''] ?? null) && 'command' === $inputArgument->getName()) {
  158. $symfonyCommandName = $this->arguments['command'] ?? null;
  159. unset($all[$key]);
  160. }
  161. if (\count($all)) {
  162. if ($symfonyCommandName) {
  163. $message = \sprintf('Too many arguments to "%s" command, expected arguments "%s".', $symfonyCommandName, implode('" "', array_keys($all)));
  164. } else {
  165. $message = \sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all)));
  166. }
  167. } elseif ($symfonyCommandName) {
  168. $message = \sprintf('No arguments expected for "%s" command, got "%s".', $symfonyCommandName, $token);
  169. } else {
  170. $message = \sprintf('No arguments expected, got "%s".', $token);
  171. }
  172. throw new RuntimeException($message);
  173. }
  174. }
  175. /**
  176. * Adds a short option value.
  177. *
  178. * @throws RuntimeException When option given doesn't exist
  179. */
  180. private function addShortOption(string $shortcut, mixed $value): void
  181. {
  182. if (!$this->definition->hasShortcut($shortcut)) {
  183. throw new RuntimeException(\sprintf('The "-%s" option does not exist.', $shortcut));
  184. }
  185. $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
  186. }
  187. /**
  188. * Adds a long option value.
  189. *
  190. * @throws RuntimeException When option given doesn't exist
  191. */
  192. private function addLongOption(string $name, mixed $value): void
  193. {
  194. if (!$this->definition->hasOption($name)) {
  195. if (!$this->definition->hasNegation($name)) {
  196. throw new RuntimeException(\sprintf('The "--%s" option does not exist.', $name));
  197. }
  198. $optionName = $this->definition->negationToName($name);
  199. if (null !== $value) {
  200. throw new RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
  201. }
  202. $this->options[$optionName] = false;
  203. return;
  204. }
  205. $option = $this->definition->getOption($name);
  206. if (null !== $value && !$option->acceptValue()) {
  207. throw new RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
  208. }
  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)) {
  214. $value = $next;
  215. } else {
  216. array_unshift($this->parsed, $next);
  217. }
  218. }
  219. if (null === $value) {
  220. if ($option->isValueRequired()) {
  221. throw new RuntimeException(\sprintf('The "--%s" option requires a value.', $name));
  222. }
  223. if (!$option->isArray() && !$option->isValueOptional()) {
  224. $value = true;
  225. }
  226. }
  227. if ($option->isArray()) {
  228. $this->options[$name][] = $value;
  229. } else {
  230. $this->options[$name] = $value;
  231. }
  232. }
  233. public function getFirstArgument(): ?string
  234. {
  235. $isOption = false;
  236. foreach ($this->tokens as $i => $token) {
  237. if ($token && '-' === $token[0]) {
  238. if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) {
  239. continue;
  240. }
  241. // If it's a long option, consider that everything after "--" is the option name.
  242. // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator)
  243. $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
  244. if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
  245. // noop
  246. } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
  247. $isOption = true;
  248. }
  249. continue;
  250. }
  251. if ($isOption) {
  252. $isOption = false;
  253. continue;
  254. }
  255. return $token;
  256. }
  257. return null;
  258. }
  259. public function hasParameterOption(string|array $values, bool $onlyParams = false): bool
  260. {
  261. $values = (array) $values;
  262. foreach ($this->tokens as $token) {
  263. if ($onlyParams && '--' === $token) {
  264. return false;
  265. }
  266. foreach ($values as $value) {
  267. // Options with values:
  268. // For long options, test for '--option=' at beginning
  269. // For short options, test for '-o' at beginning
  270. $leading = str_starts_with($value, '--') ? $value.'=' : $value;
  271. if ($token === $value || '' !== $leading && str_starts_with($token, $leading)) {
  272. return true;
  273. }
  274. }
  275. }
  276. return false;
  277. }
  278. public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed
  279. {
  280. $values = (array) $values;
  281. $tokens = $this->tokens;
  282. while (0 < \count($tokens)) {
  283. $token = array_shift($tokens);
  284. if ($onlyParams && '--' === $token) {
  285. return $default;
  286. }
  287. foreach ($values as $value) {
  288. if ($token === $value) {
  289. return array_shift($tokens);
  290. }
  291. // Options with values:
  292. // For long options, test for '--option=' at beginning
  293. // For short options, test for '-o' at beginning
  294. $leading = str_starts_with($value, '--') ? $value.'=' : $value;
  295. if ('' !== $leading && str_starts_with($token, $leading)) {
  296. return substr($token, \strlen($leading));
  297. }
  298. }
  299. }
  300. return $default;
  301. }
  302. /**
  303. * Returns un-parsed and not validated tokens.
  304. *
  305. * @param bool $strip Whether to return the raw parameters (false) or the values after the command name (true)
  306. *
  307. * @return list<string>
  308. */
  309. public function getRawTokens(bool $strip = false): array
  310. {
  311. if (!$strip) {
  312. return $this->tokens;
  313. }
  314. $parameters = [];
  315. $keep = false;
  316. foreach ($this->tokens as $value) {
  317. if (!$keep && $value === $this->getFirstArgument()) {
  318. $keep = true;
  319. continue;
  320. }
  321. if ($keep) {
  322. $parameters[] = $value;
  323. }
  324. }
  325. return $parameters;
  326. }
  327. /**
  328. * Returns a stringified representation of the args passed to the command.
  329. */
  330. public function __toString(): string
  331. {
  332. $tokens = array_map(function ($token) {
  333. if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
  334. return $match[1].$this->escapeToken($match[2]);
  335. }
  336. if ($token && '-' !== $token[0]) {
  337. return $this->escapeToken($token);
  338. }
  339. return $token;
  340. }, $this->tokens);
  341. return implode(' ', $tokens);
  342. }
  343. }