ArgvInput.php 10.0 KB

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