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>
33 * @var string|null The default command name
35 protected static $defaultName;
39 private $processTitle;
40 private $aliases = array();
42 private $hidden = false;
45 private $ignoreValidationErrors = false;
46 private $applicationDefinitionMerged = false;
47 private $applicationDefinitionMergedWithArgs = false;
49 private $synopsis = array();
50 private $usages = array();
54 * @return string|null The default command name or null when no default name is set
56 public static function getDefaultName()
58 $class = get_called_class();
59 $r = new \ReflectionProperty($class, 'defaultName');
61 return $class === $r->class ? static::$defaultName : null;
65 * @param string|null $name The name of the command; passing null means it must be set in configure()
67 * @throws LogicException When the command name is empty
69 public function __construct($name = null)
71 $this->definition = new InputDefinition();
73 if (null !== $name || null !== $name = static::getDefaultName()) {
74 $this->setName($name);
81 * Ignores validation errors.
83 * This is mainly useful for the help command.
85 public function ignoreValidationErrors()
87 $this->ignoreValidationErrors = true;
90 public function setApplication(Application $application = null)
92 $this->application = $application;
94 $this->setHelperSet($application->getHelperSet());
96 $this->helperSet = null;
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 * @return null|int null or 0 if everything went fine, or an error code
155 * @throws LogicException When this abstract method is not implemented
159 protected function execute(InputInterface $input, OutputInterface $output)
161 throw new LogicException('You must override the execute() method in the concrete command class.');
165 * Interacts with the user.
167 * This method is executed before the InputDefinition is validated.
168 * This means that this is the only place where the command can
169 * interactively ask for values of missing required arguments.
171 protected function interact(InputInterface $input, OutputInterface $output)
176 * Initializes the command just after the input has been validated.
178 * This is mainly useful when a lot of commands extends one main command
179 * where some things need to be initialized based on the input arguments and options.
181 protected function initialize(InputInterface $input, OutputInterface $output)
188 * The code to execute is either defined directly with the
189 * setCode() method or by overriding the execute() method
192 * @return int The command exit code
194 * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}.
199 public function run(InputInterface $input, OutputInterface $output)
201 // force the creation of the synopsis before the merge with the app definition
202 $this->getSynopsis(true);
203 $this->getSynopsis(false);
205 // add the application arguments and options
206 $this->mergeApplicationDefinition();
208 // bind the input against the command specific arguments/options
210 $input->bind($this->definition);
211 } catch (ExceptionInterface $e) {
212 if (!$this->ignoreValidationErrors) {
217 $this->initialize($input, $output);
219 if (null !== $this->processTitle) {
220 if (function_exists('cli_set_process_title')) {
221 if (!@cli_set_process_title($this->processTitle)) {
222 if ('Darwin' === PHP_OS) {
223 $output->writeln('<comment>Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.</comment>');
225 cli_set_process_title($this->processTitle);
228 } elseif (function_exists('setproctitle')) {
229 setproctitle($this->processTitle);
230 } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
231 $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
235 if ($input->isInteractive()) {
236 $this->interact($input, $output);
239 // The command name argument is often omitted when a command is executed directly with its run() method.
240 // It would fail the validation if we didn't make sure the command argument is present,
241 // since it's required by the application.
242 if ($input->hasArgument('command') && null === $input->getArgument('command')) {
243 $input->setArgument('command', $this->getName());
249 $statusCode = call_user_func($this->code, $input, $output);
251 $statusCode = $this->execute($input, $output);
254 return is_numeric($statusCode) ? (int) $statusCode : 0;
258 * Sets the code to execute when running this command.
260 * If this method is used, it overrides the code defined
261 * in the execute() method.
263 * @param callable $code A callable(InputInterface $input, OutputInterface $output)
267 * @throws InvalidArgumentException
271 public function setCode(callable $code)
273 if ($code instanceof \Closure) {
274 $r = new \ReflectionFunction($code);
275 if (null === $r->getClosureThis()) {
276 if (\PHP_VERSION_ID < 70000) {
277 // Bug in PHP5: https://bugs.php.net/bug.php?id=64761
278 // This means that we cannot bind static closures and therefore we must
279 // ignore any errors here. There is no way to test if the closure is
281 $code = @\Closure::bind($code, $this);
283 $code = \Closure::bind($code, $this);
294 * Merges the application definition with the command definition.
296 * This method is not part of public API and should not be used directly.
298 * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
300 public function mergeApplicationDefinition($mergeArgs = true)
302 if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
306 $this->definition->addOptions($this->application->getDefinition()->getOptions());
309 $currentArguments = $this->definition->getArguments();
310 $this->definition->setArguments($this->application->getDefinition()->getArguments());
311 $this->definition->addArguments($currentArguments);
314 $this->applicationDefinitionMerged = true;
316 $this->applicationDefinitionMergedWithArgs = true;
321 * Sets an array of argument and option instances.
323 * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
327 public function setDefinition($definition)
329 if ($definition instanceof InputDefinition) {
330 $this->definition = $definition;
332 $this->definition->setDefinition($definition);
335 $this->applicationDefinitionMerged = false;
341 * Gets the InputDefinition attached to this Command.
343 * @return InputDefinition An InputDefinition instance
345 public function getDefinition()
347 return $this->definition;
351 * Gets the InputDefinition to be used to create representations of this Command.
353 * Can be overridden to provide the original command representation when it would otherwise
354 * be changed by merging with the application InputDefinition.
356 * This method is not part of public API and should not be used directly.
358 * @return InputDefinition An InputDefinition instance
360 public function getNativeDefinition()
362 return $this->getDefinition();
368 * @param string $name The argument name
369 * @param int $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
370 * @param string $description A description text
371 * @param mixed $default The default value (for InputArgument::OPTIONAL mode only)
375 public function addArgument($name, $mode = null, $description = '', $default = null)
377 $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
385 * @param string $name The option name
386 * @param string $shortcut The shortcut (can be null)
387 * @param int $mode The option mode: One of the InputOption::VALUE_* constants
388 * @param string $description A description text
389 * @param mixed $default The default value (must be null for InputOption::VALUE_NONE)
393 public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
395 $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
401 * Sets the name of the command.
403 * This method can set both the namespace and the name if
404 * you separate them by a colon (:)
406 * $command->setName('foo:bar');
408 * @param string $name The command name
412 * @throws InvalidArgumentException When the name is invalid
414 public function setName($name)
416 $this->validateName($name);
424 * Sets the process title of the command.
426 * This feature should be used only when creating a long process command,
429 * PHP 5.5+ or the proctitle PECL library is required
431 * @param string $title The process title
435 public function setProcessTitle($title)
437 $this->processTitle = $title;
443 * Returns the command name.
445 * @return string The command name
447 public function getName()
453 * @param bool $hidden Whether or not the command should be hidden from the list of commands
455 * @return Command The current instance
457 public function setHidden($hidden)
459 $this->hidden = (bool) $hidden;
465 * @return bool whether the command should be publicly shown or not
467 public function isHidden()
469 return $this->hidden;
473 * Sets the description for the command.
475 * @param string $description The description for the command
479 public function setDescription($description)
481 $this->description = $description;
487 * Returns the description for the command.
489 * @return string The description for the command
491 public function getDescription()
493 return $this->description;
497 * Sets the help for the command.
499 * @param string $help The help for the command
503 public function setHelp($help)
511 * Returns the help for the command.
513 * @return string The help for the command
515 public function getHelp()
521 * Returns the processed help for the command replacing the %command.name% and
522 * %command.full_name% patterns with the real values dynamically.
524 * @return string The processed help for the command
526 public function getProcessedHelp()
530 $placeholders = array(
532 '%command.full_name%',
534 $replacements = array(
536 $_SERVER['PHP_SELF'].' '.$name,
539 return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
543 * Sets the aliases for the command.
545 * @param string[] $aliases An array of aliases for the command
549 * @throws InvalidArgumentException When an alias is invalid
551 public function setAliases($aliases)
553 if (!is_array($aliases) && !$aliases instanceof \Traversable) {
554 throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
557 foreach ($aliases as $alias) {
558 $this->validateName($alias);
561 $this->aliases = $aliases;
567 * Returns the aliases for the command.
569 * @return array An array of aliases for the command
571 public function getAliases()
573 return $this->aliases;
577 * Returns the synopsis for the command.
579 * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
581 * @return string The synopsis
583 public function getSynopsis($short = false)
585 $key = $short ? 'short' : 'long';
587 if (!isset($this->synopsis[$key])) {
588 $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
591 return $this->synopsis[$key];
595 * Add a command usage example.
597 * @param string $usage The usage, it'll be prefixed with the command name
601 public function addUsage($usage)
603 if (0 !== strpos($usage, $this->name)) {
604 $usage = sprintf('%s %s', $this->name, $usage);
607 $this->usages[] = $usage;
613 * Returns alternative usages of the command.
617 public function getUsages()
619 return $this->usages;
623 * Gets a helper instance by name.
625 * @param string $name The helper name
627 * @return mixed The helper value
629 * @throws LogicException if no HelperSet is defined
630 * @throws InvalidArgumentException if the helper is not defined
632 public function getHelper($name)
634 if (null === $this->helperSet) {
635 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));
638 return $this->helperSet->get($name);
642 * Validates a command name.
644 * It must be non-empty and parts can optionally be separated by ":".
646 * @param string $name
648 * @throws InvalidArgumentException When the name is invalid
650 private function validateName($name)
652 if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
653 throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));