vendor/symfony/console/Command/Command.php line 71

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