Command.php 16 KB

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