Command.php 20 KB

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