ArgvInput.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. if (\count($all)) {
  148. throw new RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
  149. }
  150. throw new RuntimeException(sprintf('No arguments expected, got "%s".', $token));
  151. }
  152. }
  153. /**
  154. * Adds a short option value.
  155. *
  156. * @throws RuntimeException When option given doesn't exist
  157. */
  158. private function addShortOption(string $shortcut, $value)
  159. {
  160. if (!$this->definition->hasShortcut($shortcut)) {
  161. throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
  162. }
  163. $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
  164. }
  165. /**
  166. * Adds a long option value.
  167. *
  168. * @throws RuntimeException When option given doesn't exist
  169. */
  170. private function addLongOption(string $name, $value)
  171. {
  172. if (!$this->definition->hasOption($name)) {
  173. throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name));
  174. }
  175. $option = $this->definition->getOption($name);
  176. if (null !== $value && !$option->acceptValue()) {
  177. throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
  178. }
  179. if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
  180. // if option accepts an optional or mandatory argument
  181. // let's see if there is one provided
  182. $next = array_shift($this->parsed);
  183. if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
  184. $value = $next;
  185. } else {
  186. array_unshift($this->parsed, $next);
  187. }
  188. }
  189. if (null === $value) {
  190. if ($option->isValueRequired()) {
  191. throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
  192. }
  193. if (!$option->isArray() && !$option->isValueOptional()) {
  194. $value = true;
  195. }
  196. }
  197. if ($option->isArray()) {
  198. $this->options[$name][] = $value;
  199. } else {
  200. $this->options[$name] = $value;
  201. }
  202. }
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function getFirstArgument()
  207. {
  208. $isOption = false;
  209. foreach ($this->tokens as $i => $token) {
  210. if ($token && '-' === $token[0]) {
  211. if (false !== strpos($token, '=') || !isset($this->tokens[$i + 1])) {
  212. continue;
  213. }
  214. // If it's a long option, consider that everything after "--" is the option name.
  215. // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator)
  216. $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
  217. if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
  218. // noop
  219. } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
  220. $isOption = true;
  221. }
  222. continue;
  223. }
  224. if ($isOption) {
  225. $isOption = false;
  226. continue;
  227. }
  228. return $token;
  229. }
  230. return null;
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. public function hasParameterOption($values, bool $onlyParams = false)
  236. {
  237. $values = (array) $values;
  238. foreach ($this->tokens as $token) {
  239. if ($onlyParams && '--' === $token) {
  240. return false;
  241. }
  242. foreach ($values as $value) {
  243. // Options with values:
  244. // For long options, test for '--option=' at beginning
  245. // For short options, test for '-o' at beginning
  246. $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
  247. if ($token === $value || '' !== $leading && 0 === strpos($token, $leading)) {
  248. return true;
  249. }
  250. }
  251. }
  252. return false;
  253. }
  254. /**
  255. * {@inheritdoc}
  256. */
  257. public function getParameterOption($values, $default = false, bool $onlyParams = false)
  258. {
  259. $values = (array) $values;
  260. $tokens = $this->tokens;
  261. while (0 < \count($tokens)) {
  262. $token = array_shift($tokens);
  263. if ($onlyParams && '--' === $token) {
  264. return $default;
  265. }
  266. foreach ($values as $value) {
  267. if ($token === $value) {
  268. return array_shift($tokens);
  269. }
  270. // Options with values:
  271. // For long options, test for '--option=' at beginning
  272. // For short options, test for '-o' at beginning
  273. $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
  274. if ('' !== $leading && 0 === strpos($token, $leading)) {
  275. return substr($token, \strlen($leading));
  276. }
  277. }
  278. }
  279. return $default;
  280. }
  281. /**
  282. * Returns a stringified representation of the args passed to the command.
  283. *
  284. * @return string
  285. */
  286. public function __toString()
  287. {
  288. $tokens = array_map(function ($token) {
  289. if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
  290. return $match[1].$this->escapeToken($match[2]);
  291. }
  292. if ($token && '-' !== $token[0]) {
  293. return $this->escapeToken($token);
  294. }
  295. return $token;
  296. }, $this->tokens);
  297. return implode(' ', $tokens);
  298. }
  299. }