"Fossies" - the Fresh Open Source Software Archive

Member "grav/vendor/symfony/console/Command/Command.php" (1 Sep 2020, 18966 Bytes) of package /linux/www/grav-v1.6.27.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "Command.php" see the Fossies "Dox" file reference documentation.

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