Command.php 22 KB

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