Command.php 19 KB

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