Command.php 20 KB

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