ArgvInput.php 13 KB

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