You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

704 lines
20 KiB

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