ArgvInput.php 11 KB

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