Drupal investigation

Command.php 20KB

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