Command.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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\Application;
  12. use Symfony\Component\Console\Attribute\AsCommand;
  13. use Symfony\Component\Console\Completion\CompletionInput;
  14. use Symfony\Component\Console\Completion\CompletionSuggestions;
  15. use Symfony\Component\Console\Completion\Suggestion;
  16. use Symfony\Component\Console\Exception\ExceptionInterface;
  17. use Symfony\Component\Console\Exception\InvalidArgumentException;
  18. use Symfony\Component\Console\Exception\LogicException;
  19. use Symfony\Component\Console\Helper\HelperInterface;
  20. use Symfony\Component\Console\Helper\HelperSet;
  21. use Symfony\Component\Console\Input\InputArgument;
  22. use Symfony\Component\Console\Input\InputDefinition;
  23. use Symfony\Component\Console\Input\InputInterface;
  24. use Symfony\Component\Console\Input\InputOption;
  25. use Symfony\Component\Console\Output\OutputInterface;
  26. /**
  27. * Base class for all commands.
  28. *
  29. * @author Fabien Potencier <fabien@symfony.com>
  30. */
  31. class Command
  32. {
  33. // see https://tldp.org/LDP/abs/html/exitcodes.html
  34. public const SUCCESS = 0;
  35. public const FAILURE = 1;
  36. public const INVALID = 2;
  37. /**
  38. * @var string|null The default command name
  39. *
  40. * @deprecated since Symfony 6.1, use the AsCommand attribute instead
  41. */
  42. protected static $defaultName;
  43. /**
  44. * @var string|null The default command description
  45. *
  46. * @deprecated since Symfony 6.1, use the AsCommand attribute instead
  47. */
  48. protected static $defaultDescription;
  49. /**
  50. * @var \Symfony\Component\Console\Application|null
  51. */
  52. private $application;
  53. /**
  54. * @var string|null
  55. */
  56. private $name;
  57. /**
  58. * @var string|null
  59. */
  60. private $processTitle;
  61. /**
  62. * @var mixed[]
  63. */
  64. private $aliases = [];
  65. /**
  66. * @var \Symfony\Component\Console\Input\InputDefinition
  67. */
  68. private $definition;
  69. /**
  70. * @var bool
  71. */
  72. private $hidden = false;
  73. /**
  74. * @var string
  75. */
  76. private $help = '';
  77. /**
  78. * @var string
  79. */
  80. private $description = '';
  81. /**
  82. * @var \Symfony\Component\Console\Input\InputDefinition|null
  83. */
  84. private $fullDefinition;
  85. /**
  86. * @var bool
  87. */
  88. private $ignoreValidationErrors = false;
  89. /**
  90. * @var \Closure|null
  91. */
  92. private $code;
  93. /**
  94. * @var mixed[]
  95. */
  96. private $synopsis = [];
  97. /**
  98. * @var mixed[]
  99. */
  100. private $usages = [];
  101. /**
  102. * @var \Symfony\Component\Console\Helper\HelperSet|null
  103. */
  104. private $helperSet;
  105. public static function getDefaultName()
  106. {
  107. $class = static::class;
  108. if ($attribute = method_exists(new \ReflectionClass($class), 'getAttributes') ? (new \ReflectionClass($class))->getAttributes(AsCommand::class) : []) {
  109. return $attribute[0]->newInstance()->name;
  110. }
  111. $r = new \ReflectionProperty($class, 'defaultName');
  112. if ($class !== $r->class || null === static::$defaultName) {
  113. return null;
  114. }
  115. trigger_deprecation('symfony/console', '6.1', 'Relying on the static property "$defaultName" for setting a command name is deprecated. Add the "%s" attribute to the "%s" class instead.', AsCommand::class, static::class);
  116. return static::$defaultName;
  117. }
  118. public static function getDefaultDescription()
  119. {
  120. $class = static::class;
  121. if ($attribute = method_exists(new \ReflectionClass($class), 'getAttributes') ? (new \ReflectionClass($class))->getAttributes(AsCommand::class) : []) {
  122. return $attribute[0]->newInstance()->description;
  123. }
  124. $r = new \ReflectionProperty($class, 'defaultDescription');
  125. if ($class !== $r->class || null === static::$defaultDescription) {
  126. return null;
  127. }
  128. trigger_deprecation('symfony/console', '6.1', 'Relying on the static property "$defaultDescription" for setting a command description is deprecated. Add the "%s" attribute to the "%s" class instead.', AsCommand::class, static::class);
  129. return static::$defaultDescription;
  130. }
  131. /**
  132. * @param string|null $name The name of the command; passing null means it must be set in configure()
  133. *
  134. * @throws LogicException When the command name is empty
  135. */
  136. public function __construct($name = null)
  137. {
  138. $this->definition = new InputDefinition();
  139. if (null === $name && null !== $name = static::getDefaultName()) {
  140. $aliases = explode('|', $name);
  141. if ('' === $name = array_shift($aliases)) {
  142. $this->setHidden(true);
  143. $name = array_shift($aliases);
  144. }
  145. $this->setAliases($aliases);
  146. }
  147. if (null !== $name) {
  148. $this->setName($name);
  149. }
  150. if ('' === $this->description) {
  151. $this->setDescription(static::getDefaultDescription() ?? '');
  152. }
  153. $this->configure();
  154. }
  155. /**
  156. * Ignores validation errors.
  157. *
  158. * This is mainly useful for the help command.
  159. *
  160. * @return void
  161. */
  162. public function ignoreValidationErrors()
  163. {
  164. $this->ignoreValidationErrors = true;
  165. }
  166. /**
  167. * @return void
  168. * @param \Symfony\Component\Console\Application|null $application
  169. */
  170. public function setApplication($application = null)
  171. {
  172. if (1 > \func_num_args()) {
  173. trigger_deprecation('symfony/console', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
  174. }
  175. $this->application = $application;
  176. if ($application) {
  177. $this->setHelperSet($application->getHelperSet());
  178. } else {
  179. $this->helperSet = null;
  180. }
  181. $this->fullDefinition = null;
  182. }
  183. /**
  184. * @return void
  185. * @param \Symfony\Component\Console\Helper\HelperSet $helperSet
  186. */
  187. public function setHelperSet($helperSet)
  188. {
  189. $this->helperSet = $helperSet;
  190. }
  191. /**
  192. * Gets the helper set.
  193. */
  194. public function getHelperSet()
  195. {
  196. return $this->helperSet;
  197. }
  198. /**
  199. * Gets the application instance for this command.
  200. */
  201. public function getApplication()
  202. {
  203. return $this->application;
  204. }
  205. /**
  206. * Checks whether the command is enabled or not in the current environment.
  207. *
  208. * Override this to check for x or y and return false if the command cannot
  209. * run properly under the current conditions.
  210. *
  211. * @return bool
  212. */
  213. public function isEnabled()
  214. {
  215. return true;
  216. }
  217. /**
  218. * Configures the current command.
  219. *
  220. * @return void
  221. */
  222. protected function configure()
  223. {
  224. }
  225. /**
  226. * Executes the current command.
  227. *
  228. * This method is not abstract because you can use this class
  229. * as a concrete class. In this case, instead of defining the
  230. * execute() method, you set the code to execute by passing
  231. * a Closure to the setCode() method.
  232. *
  233. * @return int 0 if everything went fine, or an exit code
  234. *
  235. * @throws LogicException When this abstract method is not implemented
  236. *
  237. * @see setCode()
  238. * @param \Symfony\Component\Console\Input\InputInterface $input
  239. * @param \Symfony\Component\Console\Output\OutputInterface $output
  240. */
  241. protected function execute($input, $output)
  242. {
  243. throw new LogicException('You must override the execute() method in the concrete command class.');
  244. }
  245. /**
  246. * Interacts with the user.
  247. *
  248. * This method is executed before the InputDefinition is validated.
  249. * This means that this is the only place where the command can
  250. * interactively ask for values of missing required arguments.
  251. *
  252. * @return void
  253. * @param \Symfony\Component\Console\Input\InputInterface $input
  254. * @param \Symfony\Component\Console\Output\OutputInterface $output
  255. */
  256. protected function interact($input, $output)
  257. {
  258. }
  259. /**
  260. * Initializes the command after the input has been bound and before the input
  261. * is validated.
  262. *
  263. * This is mainly useful when a lot of commands extends one main command
  264. * where some things need to be initialized based on the input arguments and options.
  265. *
  266. * @see InputInterface::bind()
  267. * @see InputInterface::validate()
  268. *
  269. * @return void
  270. * @param \Symfony\Component\Console\Input\InputInterface $input
  271. * @param \Symfony\Component\Console\Output\OutputInterface $output
  272. */
  273. protected function initialize($input, $output)
  274. {
  275. }
  276. /**
  277. * Runs the command.
  278. *
  279. * The code to execute is either defined directly with the
  280. * setCode() method or by overriding the execute() method
  281. * in a sub-class.
  282. *
  283. * @return int The command exit code
  284. *
  285. * @throws ExceptionInterface When input binding fails. Bypass this by calling {@link ignoreValidationErrors()}.
  286. *
  287. * @see setCode()
  288. * @see execute()
  289. * @param \Symfony\Component\Console\Input\InputInterface $input
  290. * @param \Symfony\Component\Console\Output\OutputInterface $output
  291. */
  292. public function run($input, $output)
  293. {
  294. // add the application arguments and options
  295. $this->mergeApplicationDefinition();
  296. // bind the input against the command specific arguments/options
  297. try {
  298. $input->bind($this->getDefinition());
  299. } catch (ExceptionInterface $e) {
  300. if (!$this->ignoreValidationErrors) {
  301. throw $e;
  302. }
  303. }
  304. $this->initialize($input, $output);
  305. if (null !== $this->processTitle) {
  306. if (\function_exists('cli_set_process_title')) {
  307. if (!@cli_set_process_title($this->processTitle)) {
  308. if ('Darwin' === \PHP_OS) {
  309. $output->writeln('<comment>Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.</comment>', OutputInterface::VERBOSITY_VERY_VERBOSE);
  310. } else {
  311. cli_set_process_title($this->processTitle);
  312. }
  313. }
  314. } elseif (\function_exists('setproctitle')) {
  315. setproctitle($this->processTitle);
  316. } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
  317. $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
  318. }
  319. }
  320. if ($input->isInteractive()) {
  321. $this->interact($input, $output);
  322. }
  323. // The command name argument is often omitted when a command is executed directly with its run() method.
  324. // It would fail the validation if we didn't make sure the command argument is present,
  325. // since it's required by the application.
  326. if ($input->hasArgument('command') && null === $input->getArgument('command')) {
  327. $input->setArgument('command', $this->getName());
  328. }
  329. $input->validate();
  330. if ($this->code) {
  331. $statusCode = ($this->code)($input, $output);
  332. } else {
  333. $statusCode = $this->execute($input, $output);
  334. if (!\is_int($statusCode)) {
  335. throw new \TypeError(sprintf('Return value of "%s::execute()" must be of the type int, "%s" returned.', static::class, get_debug_type($statusCode)));
  336. }
  337. }
  338. return is_numeric($statusCode) ? (int) $statusCode : 0;
  339. }
  340. /**
  341. * Adds suggestions to $suggestions for the current completion input (e.g. option or argument).
  342. * @param \Symfony\Component\Console\Completion\CompletionInput $input
  343. * @param \Symfony\Component\Console\Completion\CompletionSuggestions $suggestions
  344. */
  345. public function complete($input, $suggestions)
  346. {
  347. $definition = $this->getDefinition();
  348. if (CompletionInput::TYPE_OPTION_VALUE === $input->getCompletionType() && $definition->hasOption($input->getCompletionName())) {
  349. $definition->getOption($input->getCompletionName())->complete($input, $suggestions);
  350. } elseif (CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() && $definition->hasArgument($input->getCompletionName())) {
  351. $definition->getArgument($input->getCompletionName())->complete($input, $suggestions);
  352. }
  353. }
  354. /**
  355. * Sets the code to execute when running this command.
  356. *
  357. * If this method is used, it overrides the code defined
  358. * in the execute() method.
  359. *
  360. * @param callable $code A callable(InputInterface $input, OutputInterface $output)
  361. *
  362. * @return $this
  363. *
  364. * @throws InvalidArgumentException
  365. *
  366. * @see execute()
  367. */
  368. public function setCode($code)
  369. {
  370. if ($code instanceof \Closure) {
  371. $r = new \ReflectionFunction($code);
  372. if (null === $r->getClosureThis()) {
  373. set_error_handler(static function () {});
  374. try {
  375. if ($c = \Closure::bind($code, $this)) {
  376. $code = $c;
  377. }
  378. } finally {
  379. restore_error_handler();
  380. }
  381. }
  382. } else {
  383. $code = \Closure::fromCallable($code);
  384. }
  385. $this->code = $code;
  386. return $this;
  387. }
  388. /**
  389. * Merges the application definition with the command definition.
  390. *
  391. * This method is not part of public API and should not be used directly.
  392. *
  393. * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
  394. *
  395. * @internal
  396. */
  397. public function mergeApplicationDefinition($mergeArgs = true)
  398. {
  399. if (null === $this->application) {
  400. return;
  401. }
  402. $this->fullDefinition = new InputDefinition();
  403. $this->fullDefinition->setOptions($this->definition->getOptions());
  404. $this->fullDefinition->addOptions($this->application->getDefinition()->getOptions());
  405. if ($mergeArgs) {
  406. $this->fullDefinition->setArguments($this->application->getDefinition()->getArguments());
  407. $this->fullDefinition->addArguments($this->definition->getArguments());
  408. } else {
  409. $this->fullDefinition->setArguments($this->definition->getArguments());
  410. }
  411. }
  412. /**
  413. * Sets an array of argument and option instances.
  414. *
  415. * @return $this
  416. * @param mixed[]|\Symfony\Component\Console\Input\InputDefinition $definition
  417. */
  418. public function setDefinition($definition)
  419. {
  420. if ($definition instanceof InputDefinition) {
  421. $this->definition = $definition;
  422. } else {
  423. $this->definition->setDefinition($definition);
  424. }
  425. $this->fullDefinition = null;
  426. return $this;
  427. }
  428. /**
  429. * Gets the InputDefinition attached to this Command.
  430. */
  431. public function getDefinition()
  432. {
  433. return $this->fullDefinition ?? $this->getNativeDefinition();
  434. }
  435. /**
  436. * Gets the InputDefinition to be used to create representations of this Command.
  437. *
  438. * Can be overridden to provide the original command representation when it would otherwise
  439. * be changed by merging with the application InputDefinition.
  440. *
  441. * This method is not part of public API and should not be used directly.
  442. */
  443. public function getNativeDefinition()
  444. {
  445. if (!isset($this->definition)) {
  446. throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', static::class));
  447. }
  448. return $this->definition;
  449. }
  450. /**
  451. * Adds an argument.
  452. *
  453. * @param $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
  454. * @param $default The default value (for InputArgument::OPTIONAL mode only)
  455. * @param array|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion
  456. *
  457. * @return $this
  458. *
  459. * @throws InvalidArgumentException When argument mode is not valid
  460. * @param mixed $default
  461. * @param string $name
  462. * @param int|null $mode
  463. * @param string $description
  464. */
  465. public function addArgument($name, $mode = null, $description = '', $default = null /* array|\Closure $suggestedValues = null */)
  466. {
  467. $suggestedValues = 5 <= \func_num_args() ? func_get_arg(4) : [];
  468. if (!\is_array($suggestedValues) && !$suggestedValues instanceof \Closure) {
  469. throw new \TypeError(sprintf('Argument 5 passed to "%s()" must be array or \Closure, "%s" given.', __METHOD__, get_debug_type($suggestedValues)));
  470. }
  471. $this->definition->addArgument(new InputArgument($name, $mode, $description, $default, $suggestedValues));
  472. ($fullDefinition = $this->fullDefinition) ? $fullDefinition->addArgument(new InputArgument($name, $mode, $description, $default, $suggestedValues)) : null;
  473. return $this;
  474. }
  475. /**
  476. * Adds an option.
  477. *
  478. * @param $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
  479. * @param $mode The option mode: One of the InputOption::VALUE_* constants
  480. * @param $default The default value (must be null for InputOption::VALUE_NONE)
  481. * @param array|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion
  482. *
  483. * @return $this
  484. *
  485. * @throws InvalidArgumentException If option mode is invalid or incompatible
  486. * @param string|mixed[] $shortcut
  487. * @param mixed $default
  488. * @param string $name
  489. * @param int|null $mode
  490. * @param string $description
  491. */
  492. public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null /* array|\Closure $suggestedValues = [] */)
  493. {
  494. $suggestedValues = 6 <= \func_num_args() ? func_get_arg(5) : [];
  495. if (!\is_array($suggestedValues) && !$suggestedValues instanceof \Closure) {
  496. throw new \TypeError(sprintf('Argument 5 passed to "%s()" must be array or \Closure, "%s" given.', __METHOD__, get_debug_type($suggestedValues)));
  497. }
  498. $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default, $suggestedValues));
  499. ($fullDefinition = $this->fullDefinition) ? $fullDefinition->addOption(new InputOption($name, $shortcut, $mode, $description, $default, $suggestedValues)) : null;
  500. return $this;
  501. }
  502. /**
  503. * Sets the name of the command.
  504. *
  505. * This method can set both the namespace and the name if
  506. * you separate them by a colon (:)
  507. *
  508. * $command->setName('foo:bar');
  509. *
  510. * @return $this
  511. *
  512. * @throws InvalidArgumentException When the name is invalid
  513. * @param string $name
  514. */
  515. public function setName($name)
  516. {
  517. $this->validateName($name);
  518. $this->name = $name;
  519. return $this;
  520. }
  521. /**
  522. * Sets the process title of the command.
  523. *
  524. * This feature should be used only when creating a long process command,
  525. * like a daemon.
  526. *
  527. * @return $this
  528. * @param string $title
  529. */
  530. public function setProcessTitle($title)
  531. {
  532. $this->processTitle = $title;
  533. return $this;
  534. }
  535. /**
  536. * Returns the command name.
  537. */
  538. public function getName()
  539. {
  540. return $this->name;
  541. }
  542. /**
  543. * @param bool $hidden Whether or not the command should be hidden from the list of commands
  544. *
  545. * @return $this
  546. */
  547. public function setHidden($hidden = true)
  548. {
  549. $this->hidden = $hidden;
  550. return $this;
  551. }
  552. /**
  553. * @return bool whether the command should be publicly shown or not
  554. */
  555. public function isHidden()
  556. {
  557. return $this->hidden;
  558. }
  559. /**
  560. * Sets the description for the command.
  561. *
  562. * @return $this
  563. * @param string $description
  564. */
  565. public function setDescription($description)
  566. {
  567. $this->description = $description;
  568. return $this;
  569. }
  570. /**
  571. * Returns the description for the command.
  572. */
  573. public function getDescription()
  574. {
  575. return $this->description;
  576. }
  577. /**
  578. * Sets the help for the command.
  579. *
  580. * @return $this
  581. * @param string $help
  582. */
  583. public function setHelp($help)
  584. {
  585. $this->help = $help;
  586. return $this;
  587. }
  588. /**
  589. * Returns the help for the command.
  590. */
  591. public function getHelp()
  592. {
  593. return $this->help;
  594. }
  595. /**
  596. * Returns the processed help for the command replacing the %command.name% and
  597. * %command.full_name% patterns with the real values dynamically.
  598. */
  599. public function getProcessedHelp()
  600. {
  601. $name = $this->name;
  602. $isSingleCommand = ($application = $this->application) ? $application->isSingleCommand() : null;
  603. $placeholders = [
  604. '%command.name%',
  605. '%command.full_name%',
  606. ];
  607. $replacements = [
  608. $name,
  609. $isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name,
  610. ];
  611. return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
  612. }
  613. /**
  614. * Sets the aliases for the command.
  615. *
  616. * @param string[] $aliases An array of aliases for the command
  617. *
  618. * @return $this
  619. *
  620. * @throws InvalidArgumentException When an alias is invalid
  621. */
  622. public function setAliases($aliases)
  623. {
  624. $list = [];
  625. foreach ($aliases as $alias) {
  626. $this->validateName($alias);
  627. $list[] = $alias;
  628. }
  629. $this->aliases = \is_array($aliases) ? $aliases : $list;
  630. return $this;
  631. }
  632. /**
  633. * Returns the aliases for the command.
  634. */
  635. public function getAliases()
  636. {
  637. return $this->aliases;
  638. }
  639. /**
  640. * Returns the synopsis for the command.
  641. *
  642. * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
  643. */
  644. public function getSynopsis($short = false)
  645. {
  646. $key = $short ? 'short' : 'long';
  647. if (!isset($this->synopsis[$key])) {
  648. $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
  649. }
  650. return $this->synopsis[$key];
  651. }
  652. /**
  653. * Add a command usage example, it'll be prefixed with the command name.
  654. *
  655. * @return $this
  656. * @param string $usage
  657. */
  658. public function addUsage($usage)
  659. {
  660. if (strncmp($usage, $this->name, strlen($this->name)) !== 0) {
  661. $usage = sprintf('%s %s', $this->name, $usage);
  662. }
  663. $this->usages[] = $usage;
  664. return $this;
  665. }
  666. /**
  667. * Returns alternative usages of the command.
  668. */
  669. public function getUsages()
  670. {
  671. return $this->usages;
  672. }
  673. /**
  674. * Gets a helper instance by name.
  675. *
  676. * @return HelperInterface
  677. *
  678. * @throws LogicException if no HelperSet is defined
  679. * @throws InvalidArgumentException if the helper is not defined
  680. * @param string $name
  681. */
  682. public function getHelper($name)
  683. {
  684. if (null === $this->helperSet) {
  685. 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));
  686. }
  687. return $this->helperSet->get($name);
  688. }
  689. /**
  690. * Validates a command name.
  691. *
  692. * It must be non-empty and parts can optionally be separated by ":".
  693. *
  694. * @throws InvalidArgumentException When the name is invalid
  695. * @param string $name
  696. */
  697. private function validateName($name)
  698. {
  699. if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
  700. throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
  701. }
  702. }
  703. }