ArgvInput.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. /**
  12. * ArgvInput represents an input coming from the CLI arguments.
  13. *
  14. * Usage:
  15. *
  16. * $input = new ArgvInput();
  17. *
  18. * By default, the `$_SERVER['argv']` array is used for the input values.
  19. *
  20. * This can be overridden by explicitly passing the input values in the constructor:
  21. *
  22. * $input = new ArgvInput($_SERVER['argv']);
  23. *
  24. * If you pass it yourself, don't forget that the first element of the array
  25. * is the name of the running application.
  26. *
  27. * When passing an argument to the constructor, be sure that it respects
  28. * the same rules as the argv one. It's almost always better to use the
  29. * `StringInput` when you want to provide your own input.
  30. *
  31. * @author Fabien Potencier <fabien@symfony.com>
  32. *
  33. * @see http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
  34. * @see http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html#tag_12_02
  35. *
  36. * @api
  37. */
  38. class ArgvInput extends Input
  39. {
  40. private $tokens;
  41. private $parsed;
  42. /**
  43. * Constructor.
  44. *
  45. * @param array $argv An array of parameters from the CLI (in the argv format)
  46. * @param InputDefinition $definition A InputDefinition instance
  47. *
  48. * @api
  49. */
  50. public function __construct(array $argv = null, InputDefinition $definition = null)
  51. {
  52. if (null === $argv) {
  53. $argv = $_SERVER['argv'];
  54. }
  55. // strip the application name
  56. array_shift($argv);
  57. $this->tokens = $argv;
  58. parent::__construct($definition);
  59. }
  60. protected function setTokens(array $tokens)
  61. {
  62. $this->tokens = $tokens;
  63. }
  64. /**
  65. * Processes command line arguments.
  66. */
  67. protected function parse()
  68. {
  69. $parseOptions = true;
  70. $this->parsed = $this->tokens;
  71. while (null !== $token = array_shift($this->parsed)) {
  72. if ($parseOptions && '' == $token) {
  73. $this->parseArgument($token);
  74. } elseif ($parseOptions && '--' == $token) {
  75. $parseOptions = false;
  76. } elseif ($parseOptions && 0 === strpos($token, '--')) {
  77. $this->parseLongOption($token);
  78. } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
  79. $this->parseShortOption($token);
  80. } else {
  81. $this->parseArgument($token);
  82. }
  83. }
  84. }
  85. /**
  86. * Parses a short option.
  87. *
  88. * @param string $token The current token.
  89. */
  90. private function parseShortOption($token)
  91. {
  92. $name = substr($token, 1);
  93. if (strlen($name) > 1) {
  94. if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
  95. // an option with a value (with no space)
  96. $this->addShortOption($name[0], substr($name, 1));
  97. } else {
  98. $this->parseShortOptionSet($name);
  99. }
  100. } else {
  101. $this->addShortOption($name, null);
  102. }
  103. }
  104. /**
  105. * Parses a short option set.
  106. *
  107. * @param string $name The current token
  108. *
  109. * @throws \RuntimeException When option given doesn't exist
  110. */
  111. private function parseShortOptionSet($name)
  112. {
  113. $len = strlen($name);
  114. for ($i = 0; $i < $len; ++$i) {
  115. if (!$this->definition->hasShortcut($name[$i])) {
  116. throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
  117. }
  118. $option = $this->definition->getOptionForShortcut($name[$i]);
  119. if ($option->acceptValue()) {
  120. $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
  121. break;
  122. } else {
  123. $this->addLongOption($option->getName(), null);
  124. }
  125. }
  126. }
  127. /**
  128. * Parses a long option.
  129. *
  130. * @param string $token The current token
  131. */
  132. private function parseLongOption($token)
  133. {
  134. $name = substr($token, 2);
  135. if (false !== $pos = strpos($name, '=')) {
  136. $this->addLongOption(substr($name, 0, $pos), substr($name, $pos + 1));
  137. } else {
  138. $this->addLongOption($name, null);
  139. }
  140. }
  141. /**
  142. * Parses an argument.
  143. *
  144. * @param string $token The current token
  145. *
  146. * @throws \RuntimeException When too many arguments are given
  147. */
  148. private function parseArgument($token)
  149. {
  150. $c = count($this->arguments);
  151. // if input is expecting another argument, add it
  152. if ($this->definition->hasArgument($c)) {
  153. $arg = $this->definition->getArgument($c);
  154. $this->arguments[$arg->getName()] = $arg->isArray() ? array($token) : $token;
  155. // if last argument isArray(), append token to last argument
  156. } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
  157. $arg = $this->definition->getArgument($c - 1);
  158. $this->arguments[$arg->getName()][] = $token;
  159. // unexpected argument
  160. } else {
  161. throw new \RuntimeException('Too many arguments.');
  162. }
  163. }
  164. /**
  165. * Adds a short option value.
  166. *
  167. * @param string $shortcut The short option key
  168. * @param mixed $value The value for the option
  169. *
  170. * @throws \RuntimeException When option given doesn't exist
  171. */
  172. private function addShortOption($shortcut, $value)
  173. {
  174. if (!$this->definition->hasShortcut($shortcut)) {
  175. throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
  176. }
  177. $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
  178. }
  179. /**
  180. * Adds a long option value.
  181. *
  182. * @param string $name The long option key
  183. * @param mixed $value The value for the option
  184. *
  185. * @throws \RuntimeException When option given doesn't exist
  186. */
  187. private function addLongOption($name, $value)
  188. {
  189. if (!$this->definition->hasOption($name)) {
  190. throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
  191. }
  192. $option = $this->definition->getOption($name);
  193. // Convert empty values to null
  194. if (!isset($value[0])) {
  195. $value = null;
  196. }
  197. if (null !== $value && !$option->acceptValue()) {
  198. throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
  199. }
  200. if (null === $value && $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]) {
  205. $value = $next;
  206. } elseif (empty($next)) {
  207. $value = '';
  208. } else {
  209. array_unshift($this->parsed, $next);
  210. }
  211. }
  212. if (null === $value) {
  213. if ($option->isValueRequired()) {
  214. throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
  215. }
  216. if (!$option->isArray()) {
  217. $value = $option->isValueOptional() ? $option->getDefault() : true;
  218. }
  219. }
  220. if ($option->isArray()) {
  221. $this->options[$name][] = $value;
  222. } else {
  223. $this->options[$name] = $value;
  224. }
  225. }
  226. /**
  227. * Returns the first argument from the raw parameters (not parsed).
  228. *
  229. * @return string The value of the first argument or null otherwise
  230. */
  231. public function getFirstArgument()
  232. {
  233. foreach ($this->tokens as $token) {
  234. if ($token && '-' === $token[0]) {
  235. continue;
  236. }
  237. return $token;
  238. }
  239. }
  240. /**
  241. * Returns true if the raw parameters (not parsed) contain a value.
  242. *
  243. * This method is to be used to introspect the input parameters
  244. * before they have been validated. It must be used carefully.
  245. *
  246. * @param string|array $values The value(s) to look for in the raw parameters (can be an array)
  247. *
  248. * @return bool true if the value is contained in the raw parameters
  249. */
  250. public function hasParameterOption($values)
  251. {
  252. $values = (array) $values;
  253. foreach ($this->tokens as $token) {
  254. foreach ($values as $value) {
  255. if ($token === $value || 0 === strpos($token, $value.'=')) {
  256. return true;
  257. }
  258. }
  259. }
  260. return false;
  261. }
  262. /**
  263. * Returns the value of a raw option (not parsed).
  264. *
  265. * This method is to be used to introspect the input parameters
  266. * before they have been validated. It must be used carefully.
  267. *
  268. * @param string|array $values The value(s) to look for in the raw parameters (can be an array)
  269. * @param mixed $default The default value to return if no result is found
  270. *
  271. * @return mixed The option value
  272. */
  273. public function getParameterOption($values, $default = false)
  274. {
  275. $values = (array) $values;
  276. $tokens = $this->tokens;
  277. while (0 < count($tokens)) {
  278. $token = array_shift($tokens);
  279. foreach ($values as $value) {
  280. if ($token === $value || 0 === strpos($token, $value.'=')) {
  281. if (false !== $pos = strpos($token, '=')) {
  282. return substr($token, $pos + 1);
  283. }
  284. return array_shift($tokens);
  285. }
  286. }
  287. }
  288. return $default;
  289. }
  290. /**
  291. * Returns a stringified representation of the args passed to the command.
  292. *
  293. * @return string
  294. */
  295. public function __toString()
  296. {
  297. $self = $this;
  298. $tokens = array_map(function ($token) use ($self) {
  299. if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
  300. return $match[1].$self->escapeToken($match[2]);
  301. }
  302. if ($token && $token[0] !== '-') {
  303. return $self->escapeToken($token);
  304. }
  305. return $token;
  306. }, $this->tokens);
  307. return implode(' ', $tokens);
  308. }
  309. }