Command.php 18 KB

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