Command.php 19 KB

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