Command.php 19 KB

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