菜谱项目

Command.php 18KB

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