Command.php 15 KB

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