Command.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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\Command;
  11. use Symfony\Component\Console\Input\InputDefinition;
  12. use Symfony\Component\Console\Input\InputOption;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Application;
  17. use Symfony\Component\Console\Helper\HelperSet;
  18. /**
  19. * Base class for all commands.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. *
  23. * @api
  24. */
  25. class Command
  26. {
  27. private $application;
  28. private $name;
  29. private $aliases;
  30. private $definition;
  31. private $help;
  32. private $description;
  33. private $ignoreValidationErrors;
  34. private $applicationDefinitionMerged;
  35. private $code;
  36. private $synopsis;
  37. private $helperSet;
  38. /**
  39. * Constructor.
  40. *
  41. * @param string $name The name of the command
  42. *
  43. * @throws \LogicException When the command name is empty
  44. *
  45. * @api
  46. */
  47. public function __construct($name = null)
  48. {
  49. $this->definition = new InputDefinition();
  50. $this->ignoreValidationErrors = false;
  51. $this->applicationDefinitionMerged = false;
  52. $this->aliases = array();
  53. if (null !== $name) {
  54. $this->setName($name);
  55. }
  56. $this->configure();
  57. if (!$this->name) {
  58. throw new \LogicException('The command name cannot be empty.');
  59. }
  60. }
  61. /**
  62. * Ignores validation errors.
  63. *
  64. * This is mainly useful for the help command.
  65. */
  66. public function ignoreValidationErrors()
  67. {
  68. $this->ignoreValidationErrors = true;
  69. }
  70. /**
  71. * Sets the application instance for this command.
  72. *
  73. * @param Application $application An Application instance
  74. *
  75. * @api
  76. */
  77. public function setApplication(Application $application = null)
  78. {
  79. $this->application = $application;
  80. if ($application) {
  81. $this->setHelperSet($application->getHelperSet());
  82. } else {
  83. $this->helperSet = null;
  84. }
  85. }
  86. /**
  87. * Sets the helper set.
  88. *
  89. * @param HelperSet $helperSet A HelperSet instance
  90. */
  91. public function setHelperSet(HelperSet $helperSet)
  92. {
  93. $this->helperSet = $helperSet;
  94. }
  95. /**
  96. * Gets the helper set.
  97. *
  98. * @return HelperSet A HelperSet instance
  99. */
  100. public function getHelperSet()
  101. {
  102. return $this->helperSet;
  103. }
  104. /**
  105. * Gets the application instance for this command.
  106. *
  107. * @return Application An Application instance
  108. *
  109. * @api
  110. */
  111. public function getApplication()
  112. {
  113. return $this->application;
  114. }
  115. /**
  116. * Configures the current command.
  117. */
  118. protected function configure()
  119. {
  120. }
  121. /**
  122. * Executes the current command.
  123. *
  124. * This method is not abstract because you can use this class
  125. * as a concrete class. In this case, instead of defining the
  126. * execute() method, you set the code to execute by passing
  127. * a Closure to the setCode() method.
  128. *
  129. * @param InputInterface $input An InputInterface instance
  130. * @param OutputInterface $output An OutputInterface instance
  131. *
  132. * @return integer 0 if everything went fine, or an error code
  133. *
  134. * @throws \LogicException When this abstract method is not implemented
  135. * @see setCode()
  136. */
  137. protected function execute(InputInterface $input, OutputInterface $output)
  138. {
  139. throw new \LogicException('You must override the execute() method in the concrete command class.');
  140. }
  141. /**
  142. * Interacts with the user.
  143. *
  144. * @param InputInterface $input An InputInterface instance
  145. * @param OutputInterface $output An OutputInterface instance
  146. */
  147. protected function interact(InputInterface $input, OutputInterface $output)
  148. {
  149. }
  150. /**
  151. * Initializes the command just after the input has been validated.
  152. *
  153. * This is mainly useful when a lot of commands extends one main command
  154. * where some things need to be initialized based on the input arguments and options.
  155. *
  156. * @param InputInterface $input An InputInterface instance
  157. * @param OutputInterface $output An OutputInterface instance
  158. */
  159. protected function initialize(InputInterface $input, OutputInterface $output)
  160. {
  161. }
  162. /**
  163. * Runs the command.
  164. *
  165. * The code to execute is either defined directly with the
  166. * setCode() method or by overriding the execute() method
  167. * in a sub-class.
  168. *
  169. * @param InputInterface $input An InputInterface instance
  170. * @param OutputInterface $output An OutputInterface instance
  171. *
  172. * @see setCode()
  173. * @see execute()
  174. *
  175. * @api
  176. */
  177. public function run(InputInterface $input, OutputInterface $output)
  178. {
  179. // force the creation of the synopsis before the merge with the app definition
  180. $this->getSynopsis();
  181. // add the application arguments and options
  182. $this->mergeApplicationDefinition();
  183. // bind the input against the command specific arguments/options
  184. try {
  185. $input->bind($this->definition);
  186. } catch (\Exception $e) {
  187. if (!$this->ignoreValidationErrors) {
  188. throw $e;
  189. }
  190. }
  191. $this->initialize($input, $output);
  192. if ($input->isInteractive()) {
  193. $this->interact($input, $output);
  194. }
  195. $input->validate();
  196. if ($this->code) {
  197. return call_user_func($this->code, $input, $output);
  198. }
  199. return $this->execute($input, $output);
  200. }
  201. /**
  202. * Sets the code to execute when running this command.
  203. *
  204. * If this method is used, it overrides the code defined
  205. * in the execute() method.
  206. *
  207. * @param \Closure $code A \Closure
  208. *
  209. * @return Command The current instance
  210. *
  211. * @see execute()
  212. *
  213. * @api
  214. */
  215. public function setCode(\Closure $code)
  216. {
  217. $this->code = $code;
  218. return $this;
  219. }
  220. /**
  221. * Merges the application definition with the command definition.
  222. */
  223. private function mergeApplicationDefinition()
  224. {
  225. if (null === $this->application || true === $this->applicationDefinitionMerged) {
  226. return;
  227. }
  228. $this->definition->setArguments(array_merge(
  229. $this->application->getDefinition()->getArguments(),
  230. $this->definition->getArguments()
  231. ));
  232. $this->definition->addOptions($this->application->getDefinition()->getOptions());
  233. $this->applicationDefinitionMerged = true;
  234. }
  235. /**
  236. * Sets an array of argument and option instances.
  237. *
  238. * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
  239. *
  240. * @return Command The current instance
  241. *
  242. * @api
  243. */
  244. public function setDefinition($definition)
  245. {
  246. if ($definition instanceof InputDefinition) {
  247. $this->definition = $definition;
  248. } else {
  249. $this->definition->setDefinition($definition);
  250. }
  251. $this->applicationDefinitionMerged = false;
  252. return $this;
  253. }
  254. /**
  255. * Gets the InputDefinition attached to this Command.
  256. *
  257. * @return InputDefinition An InputDefinition instance
  258. *
  259. * @api
  260. */
  261. public function getDefinition()
  262. {
  263. return $this->definition;
  264. }
  265. /**
  266. * Gets the InputDefinition to be used to create XML and Text representations of this Command.
  267. *
  268. * Can be overridden to provide the original command representation when it would otherwise
  269. * be changed by merging with the application InputDefinition.
  270. *
  271. * @return InputDefinition An InputDefinition instance
  272. */
  273. protected function getNativeDefinition()
  274. {
  275. return $this->getDefinition();
  276. }
  277. /**
  278. * Adds an argument.
  279. *
  280. * @param string $name The argument name
  281. * @param integer $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
  282. * @param string $description A description text
  283. * @param mixed $default The default value (for InputArgument::OPTIONAL mode only)
  284. *
  285. * @return Command The current instance
  286. *
  287. * @api
  288. */
  289. public function addArgument($name, $mode = null, $description = '', $default = null)
  290. {
  291. $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
  292. return $this;
  293. }
  294. /**
  295. * Adds an option.
  296. *
  297. * @param string $name The option name
  298. * @param string $shortcut The shortcut (can be null)
  299. * @param integer $mode The option mode: One of the InputOption::VALUE_* constants
  300. * @param string $description A description text
  301. * @param mixed $default The default value (must be null for InputOption::VALUE_REQUIRED or InputOption::VALUE_NONE)
  302. *
  303. * @return Command The current instance
  304. *
  305. * @api
  306. */
  307. public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
  308. {
  309. $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
  310. return $this;
  311. }
  312. /**
  313. * Sets the name of the command.
  314. *
  315. * This method can set both the namespace and the name if
  316. * you separate them by a colon (:)
  317. *
  318. * $command->setName('foo:bar');
  319. *
  320. * @param string $name The command name
  321. *
  322. * @return Command The current instance
  323. *
  324. * @throws \InvalidArgumentException When command name given is empty
  325. *
  326. * @api
  327. */
  328. public function setName($name)
  329. {
  330. $this->validateName($name);
  331. $this->name = $name;
  332. return $this;
  333. }
  334. /**
  335. * Returns the command name.
  336. *
  337. * @return string The command name
  338. *
  339. * @api
  340. */
  341. public function getName()
  342. {
  343. return $this->name;
  344. }
  345. /**
  346. * Sets the description for the command.
  347. *
  348. * @param string $description The description for the command
  349. *
  350. * @return Command The current instance
  351. *
  352. * @api
  353. */
  354. public function setDescription($description)
  355. {
  356. $this->description = $description;
  357. return $this;
  358. }
  359. /**
  360. * Returns the description for the command.
  361. *
  362. * @return string The description for the command
  363. *
  364. * @api
  365. */
  366. public function getDescription()
  367. {
  368. return $this->description;
  369. }
  370. /**
  371. * Sets the help for the command.
  372. *
  373. * @param string $help The help for the command
  374. *
  375. * @return Command The current instance
  376. *
  377. * @api
  378. */
  379. public function setHelp($help)
  380. {
  381. $this->help = $help;
  382. return $this;
  383. }
  384. /**
  385. * Returns the help for the command.
  386. *
  387. * @return string The help for the command
  388. *
  389. * @api
  390. */
  391. public function getHelp()
  392. {
  393. return $this->help;
  394. }
  395. /**
  396. * Returns the processed help for the command replacing the %command.name% and
  397. * %command.full_name% patterns with the real values dynamically.
  398. *
  399. * @return string The processed help for the command
  400. */
  401. public function getProcessedHelp()
  402. {
  403. $name = $this->name;
  404. $placeholders = array(
  405. '%command.name%',
  406. '%command.full_name%'
  407. );
  408. $replacements = array(
  409. $name,
  410. $_SERVER['PHP_SELF'].' '.$name
  411. );
  412. return str_replace($placeholders, $replacements, $this->getHelp());
  413. }
  414. /**
  415. * Sets the aliases for the command.
  416. *
  417. * @param array $aliases An array of aliases for the command
  418. *
  419. * @return Command The current instance
  420. *
  421. * @api
  422. */
  423. public function setAliases($aliases)
  424. {
  425. foreach ($aliases as $alias) {
  426. $this->validateName($alias);
  427. }
  428. $this->aliases = $aliases;
  429. return $this;
  430. }
  431. /**
  432. * Returns the aliases for the command.
  433. *
  434. * @return array An array of aliases for the command
  435. *
  436. * @api
  437. */
  438. public function getAliases()
  439. {
  440. return $this->aliases;
  441. }
  442. /**
  443. * Returns the synopsis for the command.
  444. *
  445. * @return string The synopsis
  446. */
  447. public function getSynopsis()
  448. {
  449. if (null === $this->synopsis) {
  450. $this->synopsis = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis()));
  451. }
  452. return $this->synopsis;
  453. }
  454. /**
  455. * Gets a helper instance by name.
  456. *
  457. * @param string $name The helper name
  458. *
  459. * @return mixed The helper value
  460. *
  461. * @throws \InvalidArgumentException if the helper is not defined
  462. *
  463. * @api
  464. */
  465. public function getHelper($name)
  466. {
  467. return $this->helperSet->get($name);
  468. }
  469. /**
  470. * Returns a text representation of the command.
  471. *
  472. * @return string A string representing the command
  473. */
  474. public function asText()
  475. {
  476. $messages = array(
  477. '<comment>Usage:</comment>',
  478. ' '.$this->getSynopsis(),
  479. '',
  480. );
  481. if ($this->getAliases()) {
  482. $messages[] = '<comment>Aliases:</comment> <info>'.implode(', ', $this->getAliases()).'</info>';
  483. }
  484. $messages[] = $this->getNativeDefinition()->asText();
  485. if ($help = $this->getProcessedHelp()) {
  486. $messages[] = '<comment>Help:</comment>';
  487. $messages[] = ' '.implode("\n ", explode("\n", $help))."\n";
  488. }
  489. return implode("\n", $messages);
  490. }
  491. /**
  492. * Returns an XML representation of the command.
  493. *
  494. * @param Boolean $asDom Whether to return a DOM or an XML string
  495. *
  496. * @return string|DOMDocument An XML string representing the command
  497. */
  498. public function asXml($asDom = false)
  499. {
  500. $dom = new \DOMDocument('1.0', 'UTF-8');
  501. $dom->formatOutput = true;
  502. $dom->appendChild($commandXML = $dom->createElement('command'));
  503. $commandXML->setAttribute('id', $this->name);
  504. $commandXML->setAttribute('name', $this->name);
  505. $commandXML->appendChild($usageXML = $dom->createElement('usage'));
  506. $usageXML->appendChild($dom->createTextNode(sprintf($this->getSynopsis(), '')));
  507. $commandXML->appendChild($descriptionXML = $dom->createElement('description'));
  508. $descriptionXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $this->getDescription()))));
  509. $commandXML->appendChild($helpXML = $dom->createElement('help'));
  510. $help = $this->help;
  511. $helpXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $help))));
  512. $commandXML->appendChild($aliasesXML = $dom->createElement('aliases'));
  513. foreach ($this->getAliases() as $alias) {
  514. $aliasesXML->appendChild($aliasXML = $dom->createElement('alias'));
  515. $aliasXML->appendChild($dom->createTextNode($alias));
  516. }
  517. $definition = $this->getNativeDefinition()->asXml(true);
  518. $commandXML->appendChild($dom->importNode($definition->getElementsByTagName('arguments')->item(0), true));
  519. $commandXML->appendChild($dom->importNode($definition->getElementsByTagName('options')->item(0), true));
  520. return $asDom ? $dom : $dom->saveXml();
  521. }
  522. private function validateName($name)
  523. {
  524. if (!preg_match('/^[^\:]+(\:[^\:]+)*$/', $name)) {
  525. throw new \InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
  526. }
  527. }
  528. }