Command.php 19 KB

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