Command.php 20 KB

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