Command.php 13 KB

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