Command.php 18KB

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