You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

371 lines
12 KiB

3 years ago
  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. if (!$this->definition->hasNegation($name)) {
  187. throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name));
  188. }
  189. $optionName = $this->definition->negationToName($name);
  190. if (null !== $value) {
  191. throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
  192. }
  193. $this->options[$optionName] = false;
  194. return;
  195. }
  196. $option = $this->definition->getOption($name);
  197. if (null !== $value && !$option->acceptValue()) {
  198. throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
  199. }
  200. if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
  201. // if option accepts an optional or mandatory argument
  202. // let's see if there is one provided
  203. $next = array_shift($this->parsed);
  204. if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
  205. $value = $next;
  206. } else {
  207. array_unshift($this->parsed, $next);
  208. }
  209. }
  210. if (null === $value) {
  211. if ($option->isValueRequired()) {
  212. throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
  213. }
  214. if (!$option->isArray() && !$option->isValueOptional()) {
  215. $value = true;
  216. }
  217. }
  218. if ($option->isArray()) {
  219. $this->options[$name][] = $value;
  220. } else {
  221. $this->options[$name] = $value;
  222. }
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function getFirstArgument()
  228. {
  229. $isOption = false;
  230. foreach ($this->tokens as $i => $token) {
  231. if ($token && '-' === $token[0]) {
  232. if (false !== strpos($token, '=') || !isset($this->tokens[$i + 1])) {
  233. continue;
  234. }
  235. // If it's a long option, consider that everything after "--" is the option name.
  236. // Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator)
  237. $name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
  238. if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
  239. // noop
  240. } elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
  241. $isOption = true;
  242. }
  243. continue;
  244. }
  245. if ($isOption) {
  246. $isOption = false;
  247. continue;
  248. }
  249. return $token;
  250. }
  251. return null;
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function hasParameterOption($values, bool $onlyParams = false)
  257. {
  258. $values = (array) $values;
  259. foreach ($this->tokens as $token) {
  260. if ($onlyParams && '--' === $token) {
  261. return false;
  262. }
  263. foreach ($values as $value) {
  264. // Options with values:
  265. // For long options, test for '--option=' at beginning
  266. // For short options, test for '-o' at beginning
  267. $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
  268. if ($token === $value || '' !== $leading && 0 === strpos($token, $leading)) {
  269. return true;
  270. }
  271. }
  272. }
  273. return false;
  274. }
  275. /**
  276. * {@inheritdoc}
  277. */
  278. public function getParameterOption($values, $default = false, bool $onlyParams = false)
  279. {
  280. $values = (array) $values;
  281. $tokens = $this->tokens;
  282. while (0 < \count($tokens)) {
  283. $token = array_shift($tokens);
  284. if ($onlyParams && '--' === $token) {
  285. return $default;
  286. }
  287. foreach ($values as $value) {
  288. if ($token === $value) {
  289. return array_shift($tokens);
  290. }
  291. // Options with values:
  292. // For long options, test for '--option=' at beginning
  293. // For short options, test for '-o' at beginning
  294. $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
  295. if ('' !== $leading && 0 === strpos($token, $leading)) {
  296. return substr($token, \strlen($leading));
  297. }
  298. }
  299. }
  300. return $default;
  301. }
  302. /**
  303. * Returns a stringified representation of the args passed to the command.
  304. *
  305. * @return string
  306. */
  307. public function __toString()
  308. {
  309. $tokens = array_map(function ($token) {
  310. if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
  311. return $match[1].$this->escapeToken($match[2]);
  312. }
  313. if ($token && '-' !== $token[0]) {
  314. return $this->escapeToken($token);
  315. }
  316. return $token;
  317. }, $this->tokens);
  318. return implode(' ', $tokens);
  319. }
  320. }