InputDefinition.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. * A InputDefinition represents a set of valid command line arguments and options.
  13. *
  14. * Usage:
  15. *
  16. * $definition = new InputDefinition(array(
  17. * new InputArgument('name', InputArgument::REQUIRED),
  18. * new InputOption('foo', 'f', InputOption::VALUE_REQUIRED),
  19. * ));
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. *
  23. * @api
  24. */
  25. class InputDefinition
  26. {
  27. private $arguments;
  28. private $requiredCount;
  29. private $hasAnArrayArgument = false;
  30. private $hasOptional;
  31. private $options;
  32. private $shortcuts;
  33. /**
  34. * Constructor.
  35. *
  36. * @param array $definition An array of InputArgument and InputOption instance
  37. *
  38. * @api
  39. */
  40. public function __construct(array $definition = array())
  41. {
  42. $this->setDefinition($definition);
  43. }
  44. /**
  45. * Sets the definition of the input.
  46. *
  47. * @param array $definition The definition array
  48. *
  49. * @api
  50. */
  51. public function setDefinition(array $definition)
  52. {
  53. $arguments = array();
  54. $options = array();
  55. foreach ($definition as $item) {
  56. if ($item instanceof InputOption) {
  57. $options[] = $item;
  58. } else {
  59. $arguments[] = $item;
  60. }
  61. }
  62. $this->setArguments($arguments);
  63. $this->setOptions($options);
  64. }
  65. /**
  66. * Sets the InputArgument objects.
  67. *
  68. * @param array $arguments An array of InputArgument objects
  69. *
  70. * @api
  71. */
  72. public function setArguments($arguments = array())
  73. {
  74. $this->arguments = array();
  75. $this->requiredCount = 0;
  76. $this->hasOptional = false;
  77. $this->hasAnArrayArgument = false;
  78. $this->addArguments($arguments);
  79. }
  80. /**
  81. * Adds an array of InputArgument objects.
  82. *
  83. * @param InputArgument[] $arguments An array of InputArgument objects
  84. *
  85. * @api
  86. */
  87. public function addArguments($arguments = array())
  88. {
  89. if (null !== $arguments) {
  90. foreach ($arguments as $argument) {
  91. $this->addArgument($argument);
  92. }
  93. }
  94. }
  95. /**
  96. * Adds an InputArgument object.
  97. *
  98. * @param InputArgument $argument An InputArgument object
  99. *
  100. * @throws \LogicException When incorrect argument is given
  101. *
  102. * @api
  103. */
  104. public function addArgument(InputArgument $argument)
  105. {
  106. if (isset($this->arguments[$argument->getName()])) {
  107. throw new \LogicException(sprintf('An argument with name "%s" already exist.', $argument->getName()));
  108. }
  109. if ($this->hasAnArrayArgument) {
  110. throw new \LogicException('Cannot add an argument after an array argument.');
  111. }
  112. if ($argument->isRequired() && $this->hasOptional) {
  113. throw new \LogicException('Cannot add a required argument after an optional one.');
  114. }
  115. if ($argument->isArray()) {
  116. $this->hasAnArrayArgument = true;
  117. }
  118. if ($argument->isRequired()) {
  119. ++$this->requiredCount;
  120. } else {
  121. $this->hasOptional = true;
  122. }
  123. $this->arguments[$argument->getName()] = $argument;
  124. }
  125. /**
  126. * Returns an InputArgument by name or by position.
  127. *
  128. * @param string|integer $name The InputArgument name or position
  129. *
  130. * @return InputArgument An InputArgument object
  131. *
  132. * @throws \InvalidArgumentException When argument given doesn't exist
  133. *
  134. * @api
  135. */
  136. public function getArgument($name)
  137. {
  138. $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
  139. if (!$this->hasArgument($name)) {
  140. throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
  141. }
  142. return $arguments[$name];
  143. }
  144. /**
  145. * Returns true if an InputArgument object exists by name or position.
  146. *
  147. * @param string|integer $name The InputArgument name or position
  148. *
  149. * @return Boolean true if the InputArgument object exists, false otherwise
  150. *
  151. * @api
  152. */
  153. public function hasArgument($name)
  154. {
  155. $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
  156. return isset($arguments[$name]);
  157. }
  158. /**
  159. * Gets the array of InputArgument objects.
  160. *
  161. * @return array An array of InputArgument objects
  162. *
  163. * @api
  164. */
  165. public function getArguments()
  166. {
  167. return $this->arguments;
  168. }
  169. /**
  170. * Returns the number of InputArguments.
  171. *
  172. * @return integer The number of InputArguments
  173. */
  174. public function getArgumentCount()
  175. {
  176. return $this->hasAnArrayArgument ? PHP_INT_MAX : count($this->arguments);
  177. }
  178. /**
  179. * Returns the number of required InputArguments.
  180. *
  181. * @return integer The number of required InputArguments
  182. */
  183. public function getArgumentRequiredCount()
  184. {
  185. return $this->requiredCount;
  186. }
  187. /**
  188. * Gets the default values.
  189. *
  190. * @return array An array of default values
  191. */
  192. public function getArgumentDefaults()
  193. {
  194. $values = array();
  195. foreach ($this->arguments as $argument) {
  196. $values[$argument->getName()] = $argument->getDefault();
  197. }
  198. return $values;
  199. }
  200. /**
  201. * Sets the InputOption objects.
  202. *
  203. * @param array $options An array of InputOption objects
  204. *
  205. * @api
  206. */
  207. public function setOptions($options = array())
  208. {
  209. $this->options = array();
  210. $this->shortcuts = array();
  211. $this->addOptions($options);
  212. }
  213. /**
  214. * Adds an array of InputOption objects.
  215. *
  216. * @param InputOption[] $options An array of InputOption objects
  217. *
  218. * @api
  219. */
  220. public function addOptions($options = array())
  221. {
  222. foreach ($options as $option) {
  223. $this->addOption($option);
  224. }
  225. }
  226. /**
  227. * Adds an InputOption object.
  228. *
  229. * @param InputOption $option An InputOption object
  230. *
  231. * @throws \LogicException When option given already exist
  232. *
  233. * @api
  234. */
  235. public function addOption(InputOption $option)
  236. {
  237. if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) {
  238. throw new \LogicException(sprintf('An option named "%s" already exist.', $option->getName()));
  239. } elseif (isset($this->shortcuts[$option->getShortcut()]) && !$option->equals($this->options[$this->shortcuts[$option->getShortcut()]])) {
  240. throw new \LogicException(sprintf('An option with shortcut "%s" already exist.', $option->getShortcut()));
  241. }
  242. $this->options[$option->getName()] = $option;
  243. if ($option->getShortcut()) {
  244. $this->shortcuts[$option->getShortcut()] = $option->getName();
  245. }
  246. }
  247. /**
  248. * Returns an InputOption by name.
  249. *
  250. * @param string $name The InputOption name
  251. *
  252. * @return InputOption A InputOption object
  253. *
  254. * @api
  255. */
  256. public function getOption($name)
  257. {
  258. if (!$this->hasOption($name)) {
  259. throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
  260. }
  261. return $this->options[$name];
  262. }
  263. /**
  264. * Returns true if an InputOption object exists by name.
  265. *
  266. * @param string $name The InputOption name
  267. *
  268. * @return Boolean true if the InputOption object exists, false otherwise
  269. *
  270. * @api
  271. */
  272. public function hasOption($name)
  273. {
  274. return isset($this->options[$name]);
  275. }
  276. /**
  277. * Gets the array of InputOption objects.
  278. *
  279. * @return array An array of InputOption objects
  280. *
  281. * @api
  282. */
  283. public function getOptions()
  284. {
  285. return $this->options;
  286. }
  287. /**
  288. * Returns true if an InputOption object exists by shortcut.
  289. *
  290. * @param string $name The InputOption shortcut
  291. *
  292. * @return Boolean true if the InputOption object exists, false otherwise
  293. */
  294. public function hasShortcut($name)
  295. {
  296. return isset($this->shortcuts[$name]);
  297. }
  298. /**
  299. * Gets an InputOption by shortcut.
  300. *
  301. * @param string $shortcut the Shortcut name
  302. *
  303. * @return InputOption An InputOption object
  304. */
  305. public function getOptionForShortcut($shortcut)
  306. {
  307. return $this->getOption($this->shortcutToName($shortcut));
  308. }
  309. /**
  310. * Gets an array of default values.
  311. *
  312. * @return array An array of all default values
  313. */
  314. public function getOptionDefaults()
  315. {
  316. $values = array();
  317. foreach ($this->options as $option) {
  318. $values[$option->getName()] = $option->getDefault();
  319. }
  320. return $values;
  321. }
  322. /**
  323. * Returns the InputOption name given a shortcut.
  324. *
  325. * @param string $shortcut The shortcut
  326. *
  327. * @return string The InputOption name
  328. *
  329. * @throws \InvalidArgumentException When option given does not exist
  330. */
  331. private function shortcutToName($shortcut)
  332. {
  333. if (!isset($this->shortcuts[$shortcut])) {
  334. throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
  335. }
  336. return $this->shortcuts[$shortcut];
  337. }
  338. /**
  339. * Gets the synopsis.
  340. *
  341. * @return string The synopsis
  342. */
  343. public function getSynopsis()
  344. {
  345. $elements = array();
  346. foreach ($this->getOptions() as $option) {
  347. $shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
  348. $elements[] = sprintf('['.($option->isValueRequired() ? '%s--%s="..."' : ($option->isValueOptional() ? '%s--%s[="..."]' : '%s--%s')).']', $shortcut, $option->getName());
  349. }
  350. foreach ($this->getArguments() as $argument) {
  351. $elements[] = sprintf($argument->isRequired() ? '%s' : '[%s]', $argument->getName().($argument->isArray() ? '1' : ''));
  352. if ($argument->isArray()) {
  353. $elements[] = sprintf('... [%sN]', $argument->getName());
  354. }
  355. }
  356. return implode(' ', $elements);
  357. }
  358. /**
  359. * Returns a textual representation of the InputDefinition.
  360. *
  361. * @return string A string representing the InputDefinition
  362. */
  363. public function asText()
  364. {
  365. // find the largest option or argument name
  366. $max = 0;
  367. foreach ($this->getOptions() as $option) {
  368. $nameLength = strlen($option->getName()) + 2;
  369. if ($option->getShortcut()) {
  370. $nameLength += strlen($option->getShortcut()) + 3;
  371. }
  372. $max = max($max, $nameLength);
  373. }
  374. foreach ($this->getArguments() as $argument) {
  375. $max = max($max, strlen($argument->getName()));
  376. }
  377. ++$max;
  378. $text = array();
  379. if ($this->getArguments()) {
  380. $text[] = '<comment>Arguments:</comment>';
  381. foreach ($this->getArguments() as $argument) {
  382. if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault()))) {
  383. $default = sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault()));
  384. } else {
  385. $default = '';
  386. }
  387. $description = str_replace("\n", "\n".str_pad('', $max + 2, ' '), $argument->getDescription());
  388. $text[] = sprintf(" <info>%-${max}s</info> %s%s", $argument->getName(), $description, $default);
  389. }
  390. $text[] = '';
  391. }
  392. if ($this->getOptions()) {
  393. $text[] = '<comment>Options:</comment>';
  394. foreach ($this->getOptions() as $option) {
  395. if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) {
  396. $default = sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault()));
  397. } else {
  398. $default = '';
  399. }
  400. $multiple = $option->isArray() ? '<comment> (multiple values allowed)</comment>' : '';
  401. $description = str_replace("\n", "\n".str_pad('', $max + 2, ' '), $option->getDescription());
  402. $optionMax = $max - strlen($option->getName()) - 2;
  403. $text[] = sprintf(" <info>%s</info> %-${optionMax}s%s%s%s",
  404. '--'.$option->getName(),
  405. $option->getShortcut() ? sprintf('(-%s) ', $option->getShortcut()) : '',
  406. $description,
  407. $default,
  408. $multiple
  409. );
  410. }
  411. $text[] = '';
  412. }
  413. return implode("\n", $text);
  414. }
  415. /**
  416. * Returns an XML representation of the InputDefinition.
  417. *
  418. * @param Boolean $asDom Whether to return a DOM or an XML string
  419. *
  420. * @return string|DOMDocument An XML string representing the InputDefinition
  421. */
  422. public function asXml($asDom = false)
  423. {
  424. $dom = new \DOMDocument('1.0', 'UTF-8');
  425. $dom->formatOutput = true;
  426. $dom->appendChild($definitionXML = $dom->createElement('definition'));
  427. $definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
  428. foreach ($this->getArguments() as $argument) {
  429. $argumentsXML->appendChild($argumentXML = $dom->createElement('argument'));
  430. $argumentXML->setAttribute('name', $argument->getName());
  431. $argumentXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0);
  432. $argumentXML->setAttribute('is_array', $argument->isArray() ? 1 : 0);
  433. $argumentXML->appendChild($descriptionXML = $dom->createElement('description'));
  434. $descriptionXML->appendChild($dom->createTextNode($argument->getDescription()));
  435. $argumentXML->appendChild($defaultsXML = $dom->createElement('defaults'));
  436. $defaults = is_array($argument->getDefault()) ? $argument->getDefault() : (is_bool($argument->getDefault()) ? array(var_export($argument->getDefault(), true)) : ($argument->getDefault() ? array($argument->getDefault()) : array()));
  437. foreach ($defaults as $default) {
  438. $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
  439. $defaultXML->appendChild($dom->createTextNode($default));
  440. }
  441. }
  442. $definitionXML->appendChild($optionsXML = $dom->createElement('options'));
  443. foreach ($this->getOptions() as $option) {
  444. $optionsXML->appendChild($optionXML = $dom->createElement('option'));
  445. $optionXML->setAttribute('name', '--'.$option->getName());
  446. $optionXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : '');
  447. $optionXML->setAttribute('accept_value', $option->acceptValue() ? 1 : 0);
  448. $optionXML->setAttribute('is_value_required', $option->isValueRequired() ? 1 : 0);
  449. $optionXML->setAttribute('is_multiple', $option->isArray() ? 1 : 0);
  450. $optionXML->appendChild($descriptionXML = $dom->createElement('description'));
  451. $descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
  452. if ($option->acceptValue()) {
  453. $optionXML->appendChild($defaultsXML = $dom->createElement('defaults'));
  454. $defaults = is_array($option->getDefault()) ? $option->getDefault() : (is_bool($option->getDefault()) ? array(var_export($option->getDefault(), true)) : ($option->getDefault() ? array($option->getDefault()) : array()));
  455. foreach ($defaults as $default) {
  456. $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
  457. $defaultXML->appendChild($dom->createTextNode($default));
  458. }
  459. }
  460. }
  461. return $asDom ? $dom : $dom->saveXml();
  462. }
  463. private function formatDefaultValue($default)
  464. {
  465. if (is_array($default) && $default === array_values($default)) {
  466. return sprintf("array('%s')", implode("', '", $default));
  467. }
  468. return str_replace("\n", '', var_export($default, true));
  469. }
  470. }