No Description

Command.php 17KB

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