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

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