Command.php 14 KB

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