Command.php 16 KB

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