ArgvInput.php 10 KB

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