Command.php 18 KB

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