ArgvInput.php 12 KB

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