Command.php 20 KB

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