Command.php 19 KB

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