Geen omschrijving

ArgvInput.php 11KB

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