Command.php 21 KB

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