ArgvInput.php 12 KB

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