Command.php 20 KB

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