ArgvInput.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. array_unshift($this->parsed, null);
  135. }
  136. $this->addLongOption(substr($name, 0, $pos), $value);
  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. $all = $this->definition->getArguments();
  162. if (count($all)) {
  163. throw new RuntimeException(sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all))));
  164. }
  165. throw new RuntimeException(sprintf('No arguments expected, got "%s".', $token));
  166. }
  167. }
  168. /**
  169. * Adds a short option value.
  170. *
  171. * @param string $shortcut The short option key
  172. * @param mixed $value The value for the option
  173. *
  174. * @throws RuntimeException When option given doesn't exist
  175. */
  176. private function addShortOption($shortcut, $value)
  177. {
  178. if (!$this->definition->hasShortcut($shortcut)) {
  179. throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
  180. }
  181. $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
  182. }
  183. /**
  184. * Adds a long option value.
  185. *
  186. * @param string $name The long option key
  187. * @param mixed $value The value for the option
  188. *
  189. * @throws RuntimeException When option given doesn't exist
  190. */
  191. private function addLongOption($name, $value)
  192. {
  193. if (!$this->definition->hasOption($name)) {
  194. throw new RuntimeException(sprintf('The "--%s" option does not exist.', $name));
  195. }
  196. $option = $this->definition->getOption($name);
  197. // Convert empty values to null
  198. if (!isset($value[0])) {
  199. $value = null;
  200. }
  201. if (null !== $value && !$option->acceptValue()) {
  202. throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
  203. }
  204. if (null === $value && $option->acceptValue() && count($this->parsed)) {
  205. // if option accepts an optional or mandatory argument
  206. // let's see if there is one provided
  207. $next = array_shift($this->parsed);
  208. if (isset($next[0]) && '-' !== $next[0]) {
  209. $value = $next;
  210. } elseif (empty($next)) {
  211. $value = null;
  212. } else {
  213. array_unshift($this->parsed, $next);
  214. }
  215. }
  216. if (null === $value) {
  217. if ($option->isValueRequired()) {
  218. throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
  219. }
  220. if (!$option->isArray()) {
  221. $value = $option->isValueOptional() ? $option->getDefault() : true;
  222. }
  223. }
  224. if ($option->isArray()) {
  225. $this->options[$name][] = $value;
  226. } else {
  227. $this->options[$name] = $value;
  228. }
  229. }
  230. /**
  231. * {@inheritdoc}
  232. */
  233. public function getFirstArgument()
  234. {
  235. foreach ($this->tokens as $token) {
  236. if ($token && '-' === $token[0]) {
  237. continue;
  238. }
  239. return $token;
  240. }
  241. }
  242. /**
  243. * {@inheritdoc}
  244. */
  245. public function hasParameterOption($values)
  246. {
  247. $values = (array) $values;
  248. foreach ($this->tokens as $token) {
  249. foreach ($values as $value) {
  250. if ($token === $value || 0 === strpos($token, $value.'=')) {
  251. return true;
  252. }
  253. }
  254. }
  255. return false;
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. public function getParameterOption($values, $default = false)
  261. {
  262. $values = (array) $values;
  263. $tokens = $this->tokens;
  264. while (0 < count($tokens)) {
  265. $token = array_shift($tokens);
  266. foreach ($values as $value) {
  267. if ($token === $value || 0 === strpos($token, $value.'=')) {
  268. if (false !== $pos = strpos($token, '=')) {
  269. return substr($token, $pos + 1);
  270. }
  271. return array_shift($tokens);
  272. }
  273. }
  274. }
  275. return $default;
  276. }
  277. /**
  278. * Returns a stringified representation of the args passed to the command.
  279. *
  280. * @return string
  281. */
  282. public function __toString()
  283. {
  284. $self = $this;
  285. $tokens = array_map(function ($token) use ($self) {
  286. if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
  287. return $match[1].$self->escapeToken($match[2]);
  288. }
  289. if ($token && $token[0] !== '-') {
  290. return $self->escapeToken($token);
  291. }
  292. return $token;
  293. }, $this->tokens);
  294. return implode(' ', $tokens);
  295. }
  296. }