Command.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. namespace Symfony\Components\Console\Command;
  3. use Symfony\Components\Console\Input\InputDefinition;
  4. use Symfony\Components\Console\Input\InputOption;
  5. use Symfony\Components\Console\Input\InputArgument;
  6. use Symfony\Components\Console\Input\InputInterface;
  7. use Symfony\Components\Console\Output\OutputInterface;
  8. use Symfony\Components\Console\Output\Formatter;
  9. use Symfony\Components\Console\Application;
  10. /*
  11. * This file is part of the symfony framework.
  12. *
  13. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  14. *
  15. * This source file is subject to the MIT license that is bundled
  16. * with this source code in the file LICENSE.
  17. */
  18. /**
  19. * Base class for all commands.
  20. *
  21. * @package symfony
  22. * @subpackage console
  23. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  24. */
  25. class Command
  26. {
  27. protected $name;
  28. protected $namespace;
  29. protected $aliases;
  30. protected $definition;
  31. protected $help;
  32. protected $application;
  33. protected $description;
  34. protected $ignoreValidationErrors;
  35. protected $formatter;
  36. protected $applicationDefinitionMerged;
  37. protected $code;
  38. /**
  39. * Constructor.
  40. */
  41. public function __construct($name = null)
  42. {
  43. $this->definition = new InputDefinition();
  44. $this->ignoreValidationErrors = false;
  45. $this->applicationDefinitionMerged = false;
  46. $this->formatter = new Formatter();
  47. $this->aliases = array();
  48. if (null !== $name)
  49. {
  50. $this->setName($name);
  51. }
  52. $this->configure();
  53. if (!$this->name)
  54. {
  55. throw new \LogicException('The command name cannot be empty.');
  56. }
  57. }
  58. /**
  59. * Sets the application instance for this command.
  60. *
  61. * @param Application $application An Application instance
  62. */
  63. public function setApplication(Application $application = null)
  64. {
  65. $this->application = $application;
  66. }
  67. /**
  68. * Configures the current command.
  69. */
  70. protected function configure()
  71. {
  72. }
  73. /**
  74. * Executes the current command.
  75. *
  76. * @param InputInterface $input An InputInterface instance
  77. * @param OutputInterface $output An OutputInterface instance
  78. *
  79. * @return integer 0 if everything went fine, or an error code
  80. */
  81. protected function execute(InputInterface $input, OutputInterface $output)
  82. {
  83. throw new \LogicException('You must override the execute() method in the concrete command class.');
  84. }
  85. /**
  86. * Interacts with the user.
  87. *
  88. * @param InputInterface $input An InputInterface instance
  89. * @param OutputInterface $output An OutputInterface instance
  90. */
  91. protected function interact(InputInterface $input, OutputInterface $output)
  92. {
  93. }
  94. public function run(InputInterface $input, OutputInterface $output)
  95. {
  96. // add the application arguments and options
  97. $this->mergeApplicationDefinition();
  98. // bind the input against the command specific arguments/options
  99. try
  100. {
  101. $input->bind($this->definition);
  102. }
  103. catch (\Exception $e)
  104. {
  105. if (!$this->ignoreValidationErrors)
  106. {
  107. throw $e;
  108. }
  109. }
  110. if ($input->isInteractive())
  111. {
  112. $this->interact($input, $output);
  113. }
  114. $input->validate();
  115. if ($this->code)
  116. {
  117. return call_user_func($this->code, $input, $output);
  118. }
  119. else
  120. {
  121. return $this->execute($input, $output);
  122. }
  123. }
  124. /**
  125. * Sets the code to execute when running this command.
  126. *
  127. * @param \Closure $code A \Closure
  128. *
  129. * @return Command The current instance
  130. */
  131. public function setCode(\Closure $code)
  132. {
  133. $this->code = $code;
  134. return $this;
  135. }
  136. /**
  137. * Merges the application definition with the command definition.
  138. */
  139. protected function mergeApplicationDefinition()
  140. {
  141. if (null === $this->application || true === $this->applicationDefinitionMerged)
  142. {
  143. return;
  144. }
  145. $this->definition->setArguments(array_merge(
  146. $this->application->getDefinition()->getArguments(),
  147. $this->definition->getArguments()
  148. ));
  149. $this->definition->addOptions($this->application->getDefinition()->getOptions());
  150. $this->applicationDefinitionMerged = true;
  151. }
  152. /**
  153. * Sets an array of argument and option instances.
  154. *
  155. * @param array|Definition $definition An array of argument and option instances or a definition instance
  156. *
  157. * @return Command The current instance
  158. */
  159. public function setDefinition($definition)
  160. {
  161. if ($definition instanceof InputDefinition)
  162. {
  163. $this->definition = $definition;
  164. }
  165. else
  166. {
  167. $this->definition->setDefinition($definition);
  168. }
  169. $this->applicationDefinitionMerged = false;
  170. return $this;
  171. }
  172. /**
  173. * Adds an argument.
  174. *
  175. * @param string $name The argument name
  176. * @param integer $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
  177. * @param string $description A description text
  178. * @param mixed $default The default value (for InputArgument::OPTIONAL mode only)
  179. *
  180. * @return Command The current instance
  181. */
  182. public function addArgument($name, $mode = null, $description = '', $default = null)
  183. {
  184. $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
  185. return $this;
  186. }
  187. /**
  188. * Adds an option.
  189. *
  190. * @param string $name The option name
  191. * @param string $shortcut The shortcut (can be null)
  192. * @param integer $mode The option mode: self::PARAMETER_REQUIRED, self::PARAMETER_NONE or self::PARAMETER_OPTIONAL
  193. * @param string $description A description text
  194. * @param mixed $default The default value (must be null for self::PARAMETER_REQUIRED or self::PARAMETER_NONE)
  195. *
  196. * @return Command The current instance
  197. */
  198. public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
  199. {
  200. $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
  201. return $this;
  202. }
  203. /**
  204. * Sets the name of the command.
  205. *
  206. * This method can set both the namespace and the name if
  207. * you separate them by a colon (:)
  208. *
  209. * $command->setName('foo:bar');
  210. *
  211. * @param string $name The command name
  212. *
  213. * @return Command The current instance
  214. */
  215. public function setName($name)
  216. {
  217. if (false !== $pos = strpos($name, ':'))
  218. {
  219. $namespace = substr($name, 0, $pos);
  220. $name = substr($name, $pos + 1);
  221. }
  222. else
  223. {
  224. $namespace = $this->namespace;
  225. }
  226. if (!$name)
  227. {
  228. throw new \InvalidArgumentException('A command name cannot be empty');
  229. }
  230. $this->namespace = $namespace;
  231. $this->name = $name;
  232. return $this;
  233. }
  234. /**
  235. * Returns the command namespace.
  236. *
  237. * @return string The command namespace
  238. */
  239. public function getNamespace()
  240. {
  241. return $this->namespace;
  242. }
  243. /**
  244. * Returns the command name
  245. *
  246. * @return string The command name
  247. */
  248. public function getName()
  249. {
  250. return $this->name;
  251. }
  252. /**
  253. * Returns the fully qualified command name.
  254. *
  255. * @return string The fully qualified command name
  256. */
  257. public function getFullName()
  258. {
  259. return $this->getNamespace() ? $this->getNamespace().':'.$this->getName() : $this->getName();
  260. }
  261. /**
  262. * Sets the description for the command.
  263. *
  264. * @param string $description The description for the command
  265. *
  266. * @return Command The current instance
  267. */
  268. public function setDescription($description)
  269. {
  270. $this->description = $description;
  271. return $this;
  272. }
  273. /**
  274. * Returns the description for the command.
  275. *
  276. * @return string The description for the command
  277. */
  278. public function getDescription()
  279. {
  280. return $this->description;
  281. }
  282. /**
  283. * Sets the help for the command.
  284. *
  285. * @param string $help The help for the command
  286. *
  287. * @return Command The current instance
  288. */
  289. public function setHelp($help)
  290. {
  291. $this->help = $help;
  292. return $this;
  293. }
  294. /**
  295. * Returns the help for the command.
  296. *
  297. * @return string The help for the command
  298. */
  299. public function getHelp()
  300. {
  301. return $this->help;
  302. }
  303. /**
  304. * Sets the aliases for the command.
  305. *
  306. * @param array $aliases An array of aliases for the command
  307. *
  308. * @return Command The current instance
  309. */
  310. public function setAliases($aliases)
  311. {
  312. $this->aliases = $aliases;
  313. return $this;
  314. }
  315. /**
  316. * Returns the aliases for the command.
  317. *
  318. * @return array An array of aliases for the command
  319. */
  320. public function getAliases()
  321. {
  322. return $this->aliases;
  323. }
  324. /**
  325. * Returns the synopsis for the command.
  326. *
  327. * @return string The synopsis
  328. */
  329. public function getSynopsis()
  330. {
  331. return sprintf('%%s %s %s', $this->getFullName(), $this->definition->getSynopsis());
  332. }
  333. /**
  334. * Asks a question to the user.
  335. *
  336. * @param OutputInterface $output
  337. * @param string|array $question The question to ask
  338. * @param string $default The default answer if none is given by the user
  339. *
  340. * @param string The user answer
  341. */
  342. static public function ask(OutputInterface $output, $question, $default = null)
  343. {
  344. // @codeCoverageIgnoreStart
  345. $output->write($question);
  346. $ret = trim(fgets(STDIN));
  347. return $ret ? $ret : $default;
  348. // @codeCoverageIgnoreEnd
  349. }
  350. /**
  351. * Asks a confirmation to the user.
  352. *
  353. * The question will be asked until the user answer by nothing, yes, or no.
  354. *
  355. * @param OutputInterface $output
  356. * @param string|array $question The question to ask
  357. * @param Boolean $default The default answer if the user enters nothing
  358. *
  359. * @param Boolean true if the user has confirmed, false otherwise
  360. */
  361. static public function askConfirmation(OutputInterface $output, $question, $default = true)
  362. {
  363. // @codeCoverageIgnoreStart
  364. $answer = 'z';
  365. while ($answer && !in_array(strtolower($answer[0]), array('y', 'n')))
  366. {
  367. $answer = static::ask($output, $question);
  368. }
  369. if (false === $default)
  370. {
  371. return $answer && 'y' == strtolower($answer[0]);
  372. }
  373. else
  374. {
  375. return !$answer || 'y' == strtolower($answer[0]);
  376. }
  377. // @codeCoverageIgnoreEnd
  378. }
  379. /**
  380. * Asks for a value and validates the response.
  381. *
  382. * @param OutputInterface $output
  383. * @param string|array $question
  384. * @param Closure $validator
  385. * @param integer $attempts Max number of times to ask before giving up (false by default, which means infinite)
  386. *
  387. * @return mixed
  388. */
  389. static public function askAndValidate(OutputInterface $output, $question, \Closure $validator, $attempts = false)
  390. {
  391. // @codeCoverageIgnoreStart
  392. $error = null;
  393. while (false === $attempts || $attempts--)
  394. {
  395. if (null !== $error)
  396. {
  397. $output->write($this->formatter->formatBlock($error->getMessage(), 'error'));
  398. }
  399. $value = static::ask($output, $question, null);
  400. try
  401. {
  402. return $validator($value);
  403. }
  404. catch (\Exception $error)
  405. {
  406. }
  407. }
  408. throw $error;
  409. // @codeCoverageIgnoreEnd
  410. }
  411. /**
  412. * Returns a text representation of the command.
  413. *
  414. * @return string A string representing the command
  415. */
  416. public function asText()
  417. {
  418. $messages = array(
  419. '<comment>Usage:</comment>',
  420. sprintf(' '.$this->getSynopsis(), null === $this->application ? '' : $this->application->getName()),
  421. '',
  422. );
  423. if ($this->getAliases())
  424. {
  425. $messages[] = '<comment>Aliases:</comment> <info>'.implode(', ', $this->getAliases()).'</info>';
  426. }
  427. $messages[] = $this->definition->asText();
  428. if ($help = $this->getHelp())
  429. {
  430. $messages[] = '<comment>Help:</comment>';
  431. $messages[] = ' '.implode("\n ", explode("\n", $help))."\n";
  432. }
  433. return implode("\n", $messages);
  434. }
  435. /**
  436. * Returns an XML representation of the command.
  437. *
  438. * @param Boolean $asDom Whether to return a DOM or an XML string
  439. *
  440. * @return string|DOMDocument An XML string representing the command
  441. */
  442. public function asXml($asDom = false)
  443. {
  444. $dom = new \DOMDocument('1.0', 'UTF-8');
  445. $dom->formatOutput = true;
  446. $dom->appendChild($commandXML = $dom->createElement('command'));
  447. $commandXML->setAttribute('id', $this->getFullName());
  448. $commandXML->setAttribute('namespace', $this->getNamespace() ? $this->getNamespace() : '_global');
  449. $commandXML->setAttribute('name', $this->getName());
  450. $commandXML->appendChild($usageXML = $dom->createElement('usage'));
  451. $usageXML->appendChild($dom->createTextNode(sprintf($this->getSynopsis(), '')));
  452. $commandXML->appendChild($descriptionXML = $dom->createElement('description'));
  453. $descriptionXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $this->getDescription()))));
  454. $commandXML->appendChild($helpXML = $dom->createElement('help'));
  455. $help = $this->help;
  456. $helpXML->appendChild($dom->createTextNode(implode("\n ", explode("\n", $help))));
  457. $commandXML->appendChild($aliasesXML = $dom->createElement('aliases'));
  458. foreach ($this->getAliases() as $alias)
  459. {
  460. $aliasesXML->appendChild($aliasXML = $dom->createElement('alias'));
  461. $aliasXML->appendChild($dom->createTextNode($alias));
  462. }
  463. $definition = $this->definition->asXml(true);
  464. $commandXML->appendChild($dom->importNode($definition->getElementsByTagName('arguments')->item(0), true));
  465. $commandXML->appendChild($dom->importNode($definition->getElementsByTagName('options')->item(0), true));
  466. return $asDom ? $dom : $dom->saveXml();
  467. }
  468. }