ArgvInput.php 11 KB

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