Command.php 23 KB

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