Command.php 19 KB

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