4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Command;
14 use Symfony\Component\Console\Exception\ExceptionInterface;
15 use Symfony\Component\Console\Input\InputDefinition;
16 use Symfony\Component\Console\Input\InputOption;
17 use Symfony\Component\Console\Input\InputArgument;
18 use Symfony\Component\Console\Input\InputInterface;
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;
26 * Base class for all commands.
28 * @author Fabien Potencier <fabien@symfony.com>
34 private $processTitle;
35 private $aliases = array();
37 private $hidden = false;
40 private $ignoreValidationErrors = false;
41 private $applicationDefinitionMerged = false;
42 private $applicationDefinitionMergedWithArgs = false;
44 private $synopsis = array();
45 private $usages = array();
51 * @param string|null $name The name of the command; passing null means it must be set in configure()
53 * @throws LogicException When the command name is empty
55 public function __construct($name = null)
57 $this->definition = new InputDefinition();
60 $this->setName($name);
66 throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_class($this)));
71 * Ignores validation errors.
73 * This is mainly useful for the help command.
75 public function ignoreValidationErrors()
77 $this->ignoreValidationErrors = true;
81 * Sets the application instance for this command.
83 * @param Application $application An Application instance
85 public function setApplication(Application $application = null)
87 $this->application = $application;
89 $this->setHelperSet($application->getHelperSet());
91 $this->helperSet = null;
96 * Sets the helper set.
98 * @param HelperSet $helperSet A HelperSet instance
100 public function setHelperSet(HelperSet $helperSet)
102 $this->helperSet = $helperSet;
106 * Gets the helper set.
108 * @return HelperSet A HelperSet instance
110 public function getHelperSet()
112 return $this->helperSet;
116 * Gets the application instance for this command.
118 * @return Application An Application instance
120 public function getApplication()
122 return $this->application;
126 * Checks whether the command is enabled or not in the current environment.
128 * Override this to check for x or y and return false if the command can not
129 * run properly under the current conditions.
133 public function isEnabled()
139 * Configures the current command.
141 protected function configure()
146 * Executes the current command.
148 * This method is not abstract because you can use this class
149 * as a concrete class. In this case, instead of defining the
150 * execute() method, you set the code to execute by passing
151 * a Closure to the setCode() method.
153 * @param InputInterface $input An InputInterface instance
154 * @param OutputInterface $output An OutputInterface instance
156 * @return null|int null or 0 if everything went fine, or an error code
158 * @throws LogicException When this abstract method is not implemented
162 protected function execute(InputInterface $input, OutputInterface $output)
164 throw new LogicException('You must override the execute() method in the concrete command class.');
168 * Interacts with the user.
170 * This method is executed before the InputDefinition is validated.
171 * This means that this is the only place where the command can
172 * interactively ask for values of missing required arguments.
174 * @param InputInterface $input An InputInterface instance
175 * @param OutputInterface $output An OutputInterface instance
177 protected function interact(InputInterface $input, OutputInterface $output)
182 * Initializes the command just after the input has been validated.
184 * This is mainly useful when a lot of commands extends one main command
185 * where some things need to be initialized based on the input arguments and options.
187 * @param InputInterface $input An InputInterface instance
188 * @param OutputInterface $output An OutputInterface instance
190 protected function initialize(InputInterface $input, OutputInterface $output)
197 * The code to execute is either defined directly with the
198 * setCode() method or by overriding the execute() method
201 * @param InputInterface $input An InputInterface instance
202 * @param OutputInterface $output An OutputInterface instance
204 * @return int The command exit code
206 * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}.
211 public function run(InputInterface $input, OutputInterface $output)
213 // force the creation of the synopsis before the merge with the app definition
214 $this->getSynopsis(true);
215 $this->getSynopsis(false);
217 // add the application arguments and options
218 $this->mergeApplicationDefinition();
220 // bind the input against the command specific arguments/options
222 $input->bind($this->definition);
223 } catch (ExceptionInterface $e) {
224 if (!$this->ignoreValidationErrors) {
229 $this->initialize($input, $output);
231 if (null !== $this->processTitle) {
232 if (function_exists('cli_set_process_title')) {
233 if (false === @cli_set_process_title($this->processTitle)) {
234 if ('Darwin' === PHP_OS) {
235 $output->writeln('<comment>Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.</comment>');
237 $error = error_get_last();
238 trigger_error($error['message'], E_USER_WARNING);
241 } elseif (function_exists('setproctitle')) {
242 setproctitle($this->processTitle);
243 } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
244 $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
248 if ($input->isInteractive()) {
249 $this->interact($input, $output);
252 // The command name argument is often omitted when a command is executed directly with its run() method.
253 // It would fail the validation if we didn't make sure the command argument is present,
254 // since it's required by the application.
255 if ($input->hasArgument('command') && null === $input->getArgument('command')) {
256 $input->setArgument('command', $this->getName());
262 $statusCode = call_user_func($this->code, $input, $output);
264 $statusCode = $this->execute($input, $output);
267 return is_numeric($statusCode) ? (int) $statusCode : 0;
271 * Sets the code to execute when running this command.
273 * If this method is used, it overrides the code defined
274 * in the execute() method.
276 * @param callable $code A callable(InputInterface $input, OutputInterface $output)
280 * @throws InvalidArgumentException
284 public function setCode(callable $code)
286 if ($code instanceof \Closure) {
287 $r = new \ReflectionFunction($code);
288 if (null === $r->getClosureThis()) {
289 if (\PHP_VERSION_ID < 70000) {
290 // Bug in PHP5: https://bugs.php.net/bug.php?id=64761
291 // This means that we cannot bind static closures and therefore we must
292 // ignore any errors here. There is no way to test if the closure is
294 $code = @\Closure::bind($code, $this);
296 $code = \Closure::bind($code, $this);
307 * Merges the application definition with the command definition.
309 * This method is not part of public API and should not be used directly.
311 * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
313 public function mergeApplicationDefinition($mergeArgs = true)
315 if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
319 $this->definition->addOptions($this->application->getDefinition()->getOptions());
322 $currentArguments = $this->definition->getArguments();
323 $this->definition->setArguments($this->application->getDefinition()->getArguments());
324 $this->definition->addArguments($currentArguments);
327 $this->applicationDefinitionMerged = true;
329 $this->applicationDefinitionMergedWithArgs = true;
334 * Sets an array of argument and option instances.
336 * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
340 public function setDefinition($definition)
342 if ($definition instanceof InputDefinition) {
343 $this->definition = $definition;
345 $this->definition->setDefinition($definition);
348 $this->applicationDefinitionMerged = false;
354 * Gets the InputDefinition attached to this Command.
356 * @return InputDefinition An InputDefinition instance
358 public function getDefinition()
360 return $this->definition;
364 * Gets the InputDefinition to be used to create representations of this Command.
366 * Can be overridden to provide the original command representation when it would otherwise
367 * be changed by merging with the application InputDefinition.
369 * This method is not part of public API and should not be used directly.
371 * @return InputDefinition An InputDefinition instance
373 public function getNativeDefinition()
375 return $this->getDefinition();
381 * @param string $name The argument name
382 * @param int $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
383 * @param string $description A description text
384 * @param mixed $default The default value (for InputArgument::OPTIONAL mode only)
388 public function addArgument($name, $mode = null, $description = '', $default = null)
390 $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
398 * @param string $name The option name
399 * @param string $shortcut The shortcut (can be null)
400 * @param int $mode The option mode: One of the InputOption::VALUE_* constants
401 * @param string $description A description text
402 * @param mixed $default The default value (must be null for InputOption::VALUE_NONE)
406 public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
408 $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
414 * Sets the name of the command.
416 * This method can set both the namespace and the name if
417 * you separate them by a colon (:)
419 * $command->setName('foo:bar');
421 * @param string $name The command name
425 * @throws InvalidArgumentException When the name is invalid
427 public function setName($name)
429 $this->validateName($name);
437 * Sets the process title of the command.
439 * This feature should be used only when creating a long process command,
442 * PHP 5.5+ or the proctitle PECL library is required
444 * @param string $title The process title
448 public function setProcessTitle($title)
450 $this->processTitle = $title;
456 * Returns the command name.
458 * @return string The command name
460 public function getName()
466 * @param bool $hidden Whether or not the command should be hidden from the list of commands
468 * @return Command The current instance
470 public function setHidden($hidden)
472 $this->hidden = (bool) $hidden;
478 * @return bool Whether the command should be publicly shown or not.
480 public function isHidden()
482 return $this->hidden;
486 * Sets the description for the command.
488 * @param string $description The description for the command
492 public function setDescription($description)
494 $this->description = $description;
500 * Returns the description for the command.
502 * @return string The description for the command
504 public function getDescription()
506 return $this->description;
510 * Sets the help for the command.
512 * @param string $help The help for the command
516 public function setHelp($help)
524 * Returns the help for the command.
526 * @return string The help for the command
528 public function getHelp()
534 * Returns the processed help for the command replacing the %command.name% and
535 * %command.full_name% patterns with the real values dynamically.
537 * @return string The processed help for the command
539 public function getProcessedHelp()
543 $placeholders = array(
545 '%command.full_name%',
547 $replacements = array(
549 $_SERVER['PHP_SELF'].' '.$name,
552 return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
556 * Sets the aliases for the command.
558 * @param string[] $aliases An array of aliases for the command
562 * @throws InvalidArgumentException When an alias is invalid
564 public function setAliases($aliases)
566 if (!is_array($aliases) && !$aliases instanceof \Traversable) {
567 throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
570 foreach ($aliases as $alias) {
571 $this->validateName($alias);
574 $this->aliases = $aliases;
580 * Returns the aliases for the command.
582 * @return array An array of aliases for the command
584 public function getAliases()
586 return $this->aliases;
590 * Returns the synopsis for the command.
592 * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
594 * @return string The synopsis
596 public function getSynopsis($short = false)
598 $key = $short ? 'short' : 'long';
600 if (!isset($this->synopsis[$key])) {
601 $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
604 return $this->synopsis[$key];
608 * Add a command usage example.
610 * @param string $usage The usage, it'll be prefixed with the command name
614 public function addUsage($usage)
616 if (0 !== strpos($usage, $this->name)) {
617 $usage = sprintf('%s %s', $this->name, $usage);
620 $this->usages[] = $usage;
626 * Returns alternative usages of the command.
630 public function getUsages()
632 return $this->usages;
636 * Gets a helper instance by name.
638 * @param string $name The helper name
640 * @return mixed The helper value
642 * @throws LogicException if no HelperSet is defined
643 * @throws InvalidArgumentException if the helper is not defined
645 public function getHelper($name)
647 if (null === $this->helperSet) {
648 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));
651 return $this->helperSet->get($name);
655 * Validates a command name.
657 * It must be non-empty and parts can optionally be separated by ":".
659 * @param string $name
661 * @throws InvalidArgumentException When the name is invalid
663 private function validateName($name)
665 if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
666 throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));