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\Descriptor\TextDescriptor;
15 use Symfony\Component\Console\Descriptor\XmlDescriptor;
16 use Symfony\Component\Console\Exception\ExceptionInterface;
17 use Symfony\Component\Console\Input\InputDefinition;
18 use Symfony\Component\Console\Input\InputOption;
19 use Symfony\Component\Console\Input\InputArgument;
20 use Symfony\Component\Console\Input\InputInterface;
21 use Symfony\Component\Console\Output\BufferedOutput;
22 use Symfony\Component\Console\Output\OutputInterface;
23 use Symfony\Component\Console\Application;
24 use Symfony\Component\Console\Helper\HelperSet;
25 use Symfony\Component\Console\Exception\InvalidArgumentException;
26 use Symfony\Component\Console\Exception\LogicException;
29 * Base class for all commands.
31 * @author Fabien Potencier <fabien@symfony.com>
37 private $processTitle;
38 private $aliases = array();
42 private $ignoreValidationErrors = false;
43 private $applicationDefinitionMerged = false;
44 private $applicationDefinitionMergedWithArgs = false;
46 private $synopsis = array();
47 private $usages = array();
53 * @param string|null $name The name of the command; passing null means it must be set in configure()
55 * @throws LogicException When the command name is empty
57 public function __construct($name = null)
59 $this->definition = new InputDefinition();
62 $this->setName($name);
68 throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_class($this)));
73 * Ignores validation errors.
75 * This is mainly useful for the help command.
77 public function ignoreValidationErrors()
79 $this->ignoreValidationErrors = true;
83 * Sets the application instance for this command.
85 * @param Application $application An Application instance
87 public function setApplication(Application $application = null)
89 $this->application = $application;
91 $this->setHelperSet($application->getHelperSet());
93 $this->helperSet = null;
98 * Sets the helper set.
100 * @param HelperSet $helperSet A HelperSet instance
102 public function setHelperSet(HelperSet $helperSet)
104 $this->helperSet = $helperSet;
108 * Gets the helper set.
110 * @return HelperSet A HelperSet instance
112 public function getHelperSet()
114 return $this->helperSet;
118 * Gets the application instance for this command.
120 * @return Application An Application instance
122 public function getApplication()
124 return $this->application;
128 * Checks whether the command is enabled or not in the current environment.
130 * Override this to check for x or y and return false if the command can not
131 * run properly under the current conditions.
135 public function isEnabled()
141 * Configures the current command.
143 protected function configure()
148 * Executes the current command.
150 * This method is not abstract because you can use this class
151 * as a concrete class. In this case, instead of defining the
152 * execute() method, you set the code to execute by passing
153 * a Closure to the setCode() method.
155 * @param InputInterface $input An InputInterface instance
156 * @param OutputInterface $output An OutputInterface instance
158 * @return null|int null or 0 if everything went fine, or an error code
160 * @throws LogicException When this abstract method is not implemented
164 protected function execute(InputInterface $input, OutputInterface $output)
166 throw new LogicException('You must override the execute() method in the concrete command class.');
170 * Interacts with the user.
172 * This method is executed before the InputDefinition is validated.
173 * This means that this is the only place where the command can
174 * interactively ask for values of missing required arguments.
176 * @param InputInterface $input An InputInterface instance
177 * @param OutputInterface $output An OutputInterface instance
179 protected function interact(InputInterface $input, OutputInterface $output)
184 * Initializes the command just after the input has been validated.
186 * This is mainly useful when a lot of commands extends one main command
187 * where some things need to be initialized based on the input arguments and options.
189 * @param InputInterface $input An InputInterface instance
190 * @param OutputInterface $output An OutputInterface instance
192 protected function initialize(InputInterface $input, OutputInterface $output)
199 * The code to execute is either defined directly with the
200 * setCode() method or by overriding the execute() method
203 * @param InputInterface $input An InputInterface instance
204 * @param OutputInterface $output An OutputInterface instance
206 * @return int The command exit code
208 * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}.
213 public function run(InputInterface $input, OutputInterface $output)
215 // force the creation of the synopsis before the merge with the app definition
216 $this->getSynopsis(true);
217 $this->getSynopsis(false);
219 // add the application arguments and options
220 $this->mergeApplicationDefinition();
222 // bind the input against the command specific arguments/options
224 $input->bind($this->definition);
225 } catch (ExceptionInterface $e) {
226 if (!$this->ignoreValidationErrors) {
231 $this->initialize($input, $output);
233 if (null !== $this->processTitle) {
234 if (function_exists('cli_set_process_title')) {
235 if (false === @cli_set_process_title($this->processTitle)) {
236 if ('Darwin' === PHP_OS) {
237 $output->writeln('<comment>Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.</comment>');
239 $error = error_get_last();
240 trigger_error($error['message'], E_USER_WARNING);
243 } elseif (function_exists('setproctitle')) {
244 setproctitle($this->processTitle);
245 } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
246 $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
250 if ($input->isInteractive()) {
251 $this->interact($input, $output);
254 // The command name argument is often omitted when a command is executed directly with its run() method.
255 // It would fail the validation if we didn't make sure the command argument is present,
256 // since it's required by the application.
257 if ($input->hasArgument('command') && null === $input->getArgument('command')) {
258 $input->setArgument('command', $this->getName());
264 $statusCode = call_user_func($this->code, $input, $output);
266 $statusCode = $this->execute($input, $output);
269 return is_numeric($statusCode) ? (int) $statusCode : 0;
273 * Sets the code to execute when running this command.
275 * If this method is used, it overrides the code defined
276 * in the execute() method.
278 * @param callable $code A callable(InputInterface $input, OutputInterface $output)
282 * @throws InvalidArgumentException
286 public function setCode($code)
288 if (!is_callable($code)) {
289 throw new InvalidArgumentException('Invalid callable provided to Command::setCode.');
292 if (PHP_VERSION_ID >= 50400 && $code instanceof \Closure) {
293 $r = new \ReflectionFunction($code);
294 if (null === $r->getClosureThis()) {
295 if (PHP_VERSION_ID < 70000) {
296 // Bug in PHP5: https://bugs.php.net/bug.php?id=64761
297 // This means that we cannot bind static closures and therefore we must
298 // ignore any errors here. There is no way to test if the closure is
300 $code = @\Closure::bind($code, $this);
302 $code = \Closure::bind($code, $this);
313 * Merges the application definition with the command definition.
315 * This method is not part of public API and should not be used directly.
317 * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
319 public function mergeApplicationDefinition($mergeArgs = true)
321 if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
325 $this->definition->addOptions($this->application->getDefinition()->getOptions());
328 $currentArguments = $this->definition->getArguments();
329 $this->definition->setArguments($this->application->getDefinition()->getArguments());
330 $this->definition->addArguments($currentArguments);
333 $this->applicationDefinitionMerged = true;
335 $this->applicationDefinitionMergedWithArgs = true;
340 * Sets an array of argument and option instances.
342 * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
346 public function setDefinition($definition)
348 if ($definition instanceof InputDefinition) {
349 $this->definition = $definition;
351 $this->definition->setDefinition($definition);
354 $this->applicationDefinitionMerged = false;
360 * Gets the InputDefinition attached to this Command.
362 * @return InputDefinition An InputDefinition instance
364 public function getDefinition()
366 return $this->definition;
370 * Gets the InputDefinition to be used to create XML and Text representations of this Command.
372 * Can be overridden to provide the original command representation when it would otherwise
373 * be changed by merging with the application InputDefinition.
375 * This method is not part of public API and should not be used directly.
377 * @return InputDefinition An InputDefinition instance
379 public function getNativeDefinition()
381 return $this->getDefinition();
387 * @param string $name The argument name
388 * @param int $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
389 * @param string $description A description text
390 * @param mixed $default The default value (for InputArgument::OPTIONAL mode only)
394 public function addArgument($name, $mode = null, $description = '', $default = null)
396 $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
404 * @param string $name The option name
405 * @param string $shortcut The shortcut (can be null)
406 * @param int $mode The option mode: One of the InputOption::VALUE_* constants
407 * @param string $description A description text
408 * @param mixed $default The default value (must be null for InputOption::VALUE_NONE)
412 public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
414 $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
420 * Sets the name of the command.
422 * This method can set both the namespace and the name if
423 * you separate them by a colon (:)
425 * $command->setName('foo:bar');
427 * @param string $name The command name
431 * @throws InvalidArgumentException When the name is invalid
433 public function setName($name)
435 $this->validateName($name);
443 * Sets the process title of the command.
445 * This feature should be used only when creating a long process command,
448 * PHP 5.5+ or the proctitle PECL library is required
450 * @param string $title The process title
454 public function setProcessTitle($title)
456 $this->processTitle = $title;
462 * Returns the command name.
464 * @return string The command name
466 public function getName()
472 * Sets the description for the command.
474 * @param string $description The description for the command
478 public function setDescription($description)
480 $this->description = $description;
486 * Returns the description for the command.
488 * @return string The description for the command
490 public function getDescription()
492 return $this->description;
496 * Sets the help for the command.
498 * @param string $help The help for the command
502 public function setHelp($help)
510 * Returns the help for the command.
512 * @return string The help for the command
514 public function getHelp()
520 * Returns the processed help for the command replacing the %command.name% and
521 * %command.full_name% patterns with the real values dynamically.
523 * @return string The processed help for the command
525 public function getProcessedHelp()
529 $placeholders = array(
531 '%command.full_name%',
533 $replacements = array(
535 $_SERVER['PHP_SELF'].' '.$name,
538 return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
542 * Sets the aliases for the command.
544 * @param string[] $aliases An array of aliases for the command
548 * @throws InvalidArgumentException When an alias is invalid
550 public function setAliases($aliases)
552 if (!is_array($aliases) && !$aliases instanceof \Traversable) {
553 throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
556 foreach ($aliases as $alias) {
557 $this->validateName($alias);
560 $this->aliases = $aliases;
566 * Returns the aliases for the command.
568 * @return array An array of aliases for the command
570 public function getAliases()
572 return $this->aliases;
576 * Returns the synopsis for the command.
578 * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
580 * @return string The synopsis
582 public function getSynopsis($short = false)
584 $key = $short ? 'short' : 'long';
586 if (!isset($this->synopsis[$key])) {
587 $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
590 return $this->synopsis[$key];
594 * Add a command usage example.
596 * @param string $usage The usage, it'll be prefixed with the command name
600 public function addUsage($usage)
602 if (0 !== strpos($usage, $this->name)) {
603 $usage = sprintf('%s %s', $this->name, $usage);
606 $this->usages[] = $usage;
612 * Returns alternative usages of the command.
616 public function getUsages()
618 return $this->usages;
622 * Gets a helper instance by name.
624 * @param string $name The helper name
626 * @return mixed The helper value
628 * @throws LogicException if no HelperSet is defined
629 * @throws InvalidArgumentException if the helper is not defined
631 public function getHelper($name)
633 if (null === $this->helperSet) {
634 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));
637 return $this->helperSet->get($name);
641 * Returns a text representation of the command.
643 * @return string A string representing the command
645 * @deprecated since version 2.3, to be removed in 3.0.
647 public function asText()
649 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
651 $descriptor = new TextDescriptor();
652 $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
653 $descriptor->describe($output, $this, array('raw_output' => true));
655 return $output->fetch();
659 * Returns an XML representation of the command.
661 * @param bool $asDom Whether to return a DOM or an XML string
663 * @return string|\DOMDocument An XML string representing the command
665 * @deprecated since version 2.3, to be removed in 3.0.
667 public function asXml($asDom = false)
669 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
671 $descriptor = new XmlDescriptor();
674 return $descriptor->getCommandDocument($this);
677 $output = new BufferedOutput();
678 $descriptor->describe($output, $this);
680 return $output->fetch();
684 * Validates a command name.
686 * It must be non-empty and parts can optionally be separated by ":".
688 * @param string $name
690 * @throws InvalidArgumentException When the name is invalid
692 private function validateName($name)
694 if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
695 throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));