Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Console\Command; Chris@0: Chris@17: use Symfony\Component\Console\Application; Chris@0: use Symfony\Component\Console\Exception\ExceptionInterface; Chris@0: use Symfony\Component\Console\Exception\InvalidArgumentException; Chris@0: use Symfony\Component\Console\Exception\LogicException; Chris@17: use Symfony\Component\Console\Helper\HelperSet; Chris@17: use Symfony\Component\Console\Input\InputArgument; Chris@17: use Symfony\Component\Console\Input\InputDefinition; Chris@17: use Symfony\Component\Console\Input\InputInterface; Chris@17: use Symfony\Component\Console\Input\InputOption; Chris@17: use Symfony\Component\Console\Output\OutputInterface; Chris@0: Chris@0: /** Chris@0: * Base class for all commands. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class Command Chris@0: { Chris@14: /** Chris@14: * @var string|null The default command name Chris@14: */ Chris@14: protected static $defaultName; Chris@14: Chris@0: private $application; Chris@0: private $name; Chris@0: private $processTitle; Chris@17: private $aliases = []; Chris@0: private $definition; Chris@0: private $hidden = false; Chris@0: private $help; Chris@0: private $description; Chris@0: private $ignoreValidationErrors = false; Chris@0: private $applicationDefinitionMerged = false; Chris@0: private $applicationDefinitionMergedWithArgs = false; Chris@0: private $code; Chris@17: private $synopsis = []; Chris@17: private $usages = []; Chris@0: private $helperSet; Chris@0: Chris@0: /** Chris@14: * @return string|null The default command name or null when no default name is set Chris@14: */ Chris@14: public static function getDefaultName() Chris@14: { Chris@17: $class = \get_called_class(); Chris@14: $r = new \ReflectionProperty($class, 'defaultName'); Chris@14: Chris@14: return $class === $r->class ? static::$defaultName : null; Chris@14: } Chris@14: Chris@14: /** Chris@0: * @param string|null $name The name of the command; passing null means it must be set in configure() Chris@0: * Chris@0: * @throws LogicException When the command name is empty Chris@0: */ Chris@0: public function __construct($name = null) Chris@0: { Chris@0: $this->definition = new InputDefinition(); Chris@0: Chris@14: if (null !== $name || null !== $name = static::getDefaultName()) { Chris@0: $this->setName($name); Chris@0: } Chris@0: Chris@0: $this->configure(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Ignores validation errors. Chris@0: * Chris@0: * This is mainly useful for the help command. Chris@0: */ Chris@0: public function ignoreValidationErrors() Chris@0: { Chris@0: $this->ignoreValidationErrors = true; Chris@0: } Chris@0: Chris@0: public function setApplication(Application $application = null) Chris@0: { Chris@0: $this->application = $application; Chris@0: if ($application) { Chris@0: $this->setHelperSet($application->getHelperSet()); Chris@0: } else { Chris@0: $this->helperSet = null; Chris@0: } Chris@0: } Chris@0: Chris@0: public function setHelperSet(HelperSet $helperSet) Chris@0: { Chris@0: $this->helperSet = $helperSet; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the helper set. Chris@0: * Chris@0: * @return HelperSet A HelperSet instance Chris@0: */ Chris@0: public function getHelperSet() Chris@0: { Chris@0: return $this->helperSet; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the application instance for this command. Chris@0: * Chris@0: * @return Application An Application instance Chris@0: */ Chris@0: public function getApplication() Chris@0: { Chris@0: return $this->application; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether the command is enabled or not in the current environment. Chris@0: * Chris@0: * Override this to check for x or y and return false if the command can not Chris@0: * run properly under the current conditions. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function isEnabled() Chris@0: { Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Configures the current command. Chris@0: */ Chris@0: protected function configure() Chris@0: { Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes the current command. Chris@0: * Chris@0: * This method is not abstract because you can use this class Chris@0: * as a concrete class. In this case, instead of defining the Chris@0: * execute() method, you set the code to execute by passing Chris@0: * a Closure to the setCode() method. Chris@0: * Chris@17: * @return int|null null or 0 if everything went fine, or an error code Chris@0: * Chris@0: * @throws LogicException When this abstract method is not implemented Chris@0: * Chris@0: * @see setCode() Chris@0: */ Chris@0: protected function execute(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: throw new LogicException('You must override the execute() method in the concrete command class.'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Interacts with the user. Chris@0: * Chris@0: * This method is executed before the InputDefinition is validated. Chris@0: * This means that this is the only place where the command can Chris@0: * interactively ask for values of missing required arguments. Chris@0: */ Chris@0: protected function interact(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: } Chris@0: Chris@0: /** Chris@17: * Initializes the command after the input has been bound and before the input Chris@17: * is validated. Chris@0: * Chris@0: * This is mainly useful when a lot of commands extends one main command Chris@0: * where some things need to be initialized based on the input arguments and options. Chris@17: * Chris@17: * @see InputInterface::bind() Chris@17: * @see InputInterface::validate() Chris@0: */ Chris@0: protected function initialize(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs the command. Chris@0: * Chris@0: * The code to execute is either defined directly with the Chris@0: * setCode() method or by overriding the execute() method Chris@0: * in a sub-class. Chris@0: * Chris@0: * @return int The command exit code Chris@0: * Chris@0: * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}. Chris@0: * Chris@0: * @see setCode() Chris@0: * @see execute() Chris@0: */ Chris@0: public function run(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: // force the creation of the synopsis before the merge with the app definition Chris@0: $this->getSynopsis(true); Chris@0: $this->getSynopsis(false); Chris@0: Chris@0: // add the application arguments and options Chris@0: $this->mergeApplicationDefinition(); Chris@0: Chris@0: // bind the input against the command specific arguments/options Chris@0: try { Chris@0: $input->bind($this->definition); Chris@0: } catch (ExceptionInterface $e) { Chris@0: if (!$this->ignoreValidationErrors) { Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: $this->initialize($input, $output); Chris@0: Chris@0: if (null !== $this->processTitle) { Chris@17: if (\function_exists('cli_set_process_title')) { Chris@16: if (!@cli_set_process_title($this->processTitle)) { Chris@0: if ('Darwin' === PHP_OS) { Chris@17: $output->writeln('Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.', OutputInterface::VERBOSITY_VERY_VERBOSE); Chris@0: } else { Chris@16: cli_set_process_title($this->processTitle); Chris@0: } Chris@0: } Chris@17: } elseif (\function_exists('setproctitle')) { Chris@0: setproctitle($this->processTitle); Chris@0: } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) { Chris@0: $output->writeln('Install the proctitle PECL to be able to change the process title.'); Chris@0: } Chris@0: } Chris@0: Chris@0: if ($input->isInteractive()) { Chris@0: $this->interact($input, $output); Chris@0: } Chris@0: Chris@0: // The command name argument is often omitted when a command is executed directly with its run() method. Chris@0: // It would fail the validation if we didn't make sure the command argument is present, Chris@0: // since it's required by the application. Chris@0: if ($input->hasArgument('command') && null === $input->getArgument('command')) { Chris@0: $input->setArgument('command', $this->getName()); Chris@0: } Chris@0: Chris@0: $input->validate(); Chris@0: Chris@0: if ($this->code) { Chris@17: $statusCode = \call_user_func($this->code, $input, $output); Chris@0: } else { Chris@0: $statusCode = $this->execute($input, $output); Chris@0: } Chris@0: Chris@0: return is_numeric($statusCode) ? (int) $statusCode : 0; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the code to execute when running this command. Chris@0: * Chris@0: * If this method is used, it overrides the code defined Chris@0: * in the execute() method. Chris@0: * Chris@0: * @param callable $code A callable(InputInterface $input, OutputInterface $output) Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: * Chris@0: * @see execute() Chris@0: */ Chris@0: public function setCode(callable $code) Chris@0: { Chris@0: if ($code instanceof \Closure) { Chris@0: $r = new \ReflectionFunction($code); Chris@0: if (null === $r->getClosureThis()) { Chris@12: if (\PHP_VERSION_ID < 70000) { Chris@0: // Bug in PHP5: https://bugs.php.net/bug.php?id=64761 Chris@0: // This means that we cannot bind static closures and therefore we must Chris@0: // ignore any errors here. There is no way to test if the closure is Chris@0: // bindable. Chris@0: $code = @\Closure::bind($code, $this); Chris@0: } else { Chris@0: $code = \Closure::bind($code, $this); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $this->code = $code; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Merges the application definition with the command definition. Chris@0: * Chris@0: * This method is not part of public API and should not be used directly. Chris@0: * Chris@0: * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments Chris@0: */ Chris@0: public function mergeApplicationDefinition($mergeArgs = true) Chris@0: { Chris@0: if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) { Chris@0: return; Chris@0: } Chris@0: Chris@0: $this->definition->addOptions($this->application->getDefinition()->getOptions()); Chris@0: Chris@17: $this->applicationDefinitionMerged = true; Chris@17: Chris@0: if ($mergeArgs) { Chris@0: $currentArguments = $this->definition->getArguments(); Chris@0: $this->definition->setArguments($this->application->getDefinition()->getArguments()); Chris@0: $this->definition->addArguments($currentArguments); Chris@0: Chris@0: $this->applicationDefinitionMergedWithArgs = true; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets an array of argument and option instances. Chris@0: * Chris@0: * @param array|InputDefinition $definition An array of argument and option instances or a definition instance Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setDefinition($definition) Chris@0: { Chris@0: if ($definition instanceof InputDefinition) { Chris@0: $this->definition = $definition; Chris@0: } else { Chris@0: $this->definition->setDefinition($definition); Chris@0: } Chris@0: Chris@0: $this->applicationDefinitionMerged = false; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the InputDefinition attached to this Command. Chris@0: * Chris@0: * @return InputDefinition An InputDefinition instance Chris@0: */ Chris@0: public function getDefinition() Chris@0: { Chris@0: return $this->definition; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the InputDefinition to be used to create representations of this Command. Chris@0: * Chris@0: * Can be overridden to provide the original command representation when it would otherwise Chris@0: * be changed by merging with the application InputDefinition. Chris@0: * Chris@0: * This method is not part of public API and should not be used directly. Chris@0: * Chris@0: * @return InputDefinition An InputDefinition instance Chris@0: */ Chris@0: public function getNativeDefinition() Chris@0: { Chris@0: return $this->getDefinition(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds an argument. Chris@0: * Chris@17: * @param string $name The argument name Chris@17: * @param int|null $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL Chris@17: * @param string $description A description text Chris@17: * @param string|string[]|null $default The default value (for InputArgument::OPTIONAL mode only) Chris@17: * Chris@17: * @throws InvalidArgumentException When argument mode is not valid Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function addArgument($name, $mode = null, $description = '', $default = null) Chris@0: { Chris@0: $this->definition->addArgument(new InputArgument($name, $mode, $description, $default)); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds an option. Chris@0: * Chris@17: * @param string $name The option name Chris@17: * @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts Chris@17: * @param int|null $mode The option mode: One of the InputOption::VALUE_* constants Chris@17: * @param string $description A description text Chris@17: * @param string|string[]|int|bool|null $default The default value (must be null for InputOption::VALUE_NONE) Chris@17: * Chris@17: * @throws InvalidArgumentException If option mode is invalid or incompatible Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null) Chris@0: { Chris@0: $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default)); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the name of the command. Chris@0: * Chris@0: * This method can set both the namespace and the name if Chris@0: * you separate them by a colon (:) Chris@0: * Chris@0: * $command->setName('foo:bar'); Chris@0: * Chris@0: * @param string $name The command name Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws InvalidArgumentException When the name is invalid Chris@0: */ Chris@0: public function setName($name) Chris@0: { Chris@0: $this->validateName($name); Chris@0: Chris@0: $this->name = $name; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the process title of the command. Chris@0: * Chris@0: * This feature should be used only when creating a long process command, Chris@0: * like a daemon. Chris@0: * Chris@0: * PHP 5.5+ or the proctitle PECL library is required Chris@0: * Chris@0: * @param string $title The process title Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setProcessTitle($title) Chris@0: { Chris@0: $this->processTitle = $title; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the command name. Chris@0: * Chris@0: * @return string The command name Chris@0: */ Chris@0: public function getName() Chris@0: { Chris@0: return $this->name; Chris@0: } Chris@0: Chris@0: /** Chris@0: * @param bool $hidden Whether or not the command should be hidden from the list of commands Chris@0: * Chris@0: * @return Command The current instance Chris@0: */ Chris@0: public function setHidden($hidden) Chris@0: { Chris@0: $this->hidden = (bool) $hidden; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@14: * @return bool whether the command should be publicly shown or not Chris@0: */ Chris@0: public function isHidden() Chris@0: { Chris@0: return $this->hidden; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the description for the command. Chris@0: * Chris@0: * @param string $description The description for the command Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setDescription($description) Chris@0: { Chris@0: $this->description = $description; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the description for the command. Chris@0: * Chris@0: * @return string The description for the command Chris@0: */ Chris@0: public function getDescription() Chris@0: { Chris@0: return $this->description; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the help for the command. Chris@0: * Chris@0: * @param string $help The help for the command Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setHelp($help) Chris@0: { Chris@0: $this->help = $help; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the help for the command. Chris@0: * Chris@0: * @return string The help for the command Chris@0: */ Chris@0: public function getHelp() Chris@0: { Chris@0: return $this->help; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the processed help for the command replacing the %command.name% and Chris@0: * %command.full_name% patterns with the real values dynamically. Chris@0: * Chris@0: * @return string The processed help for the command Chris@0: */ Chris@0: public function getProcessedHelp() Chris@0: { Chris@0: $name = $this->name; Chris@17: $isSingleCommand = $this->application && $this->application->isSingleCommand(); Chris@0: Chris@17: $placeholders = [ Chris@0: '%command.name%', Chris@0: '%command.full_name%', Chris@17: ]; Chris@17: $replacements = [ Chris@0: $name, Chris@17: $isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name, Chris@17: ]; Chris@0: Chris@0: return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the aliases for the command. Chris@0: * Chris@0: * @param string[] $aliases An array of aliases for the command Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws InvalidArgumentException When an alias is invalid Chris@0: */ Chris@0: public function setAliases($aliases) Chris@0: { Chris@17: if (!\is_array($aliases) && !$aliases instanceof \Traversable) { Chris@0: throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable'); Chris@0: } Chris@0: Chris@0: foreach ($aliases as $alias) { Chris@0: $this->validateName($alias); Chris@0: } Chris@0: Chris@0: $this->aliases = $aliases; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the aliases for the command. Chris@0: * Chris@0: * @return array An array of aliases for the command Chris@0: */ Chris@0: public function getAliases() Chris@0: { Chris@0: return $this->aliases; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the synopsis for the command. Chris@0: * Chris@0: * @param bool $short Whether to show the short version of the synopsis (with options folded) or not Chris@0: * Chris@0: * @return string The synopsis Chris@0: */ Chris@0: public function getSynopsis($short = false) Chris@0: { Chris@0: $key = $short ? 'short' : 'long'; Chris@0: Chris@0: if (!isset($this->synopsis[$key])) { Chris@0: $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short))); Chris@0: } Chris@0: Chris@0: return $this->synopsis[$key]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Add a command usage example. Chris@0: * Chris@0: * @param string $usage The usage, it'll be prefixed with the command name Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function addUsage($usage) Chris@0: { Chris@0: if (0 !== strpos($usage, $this->name)) { Chris@0: $usage = sprintf('%s %s', $this->name, $usage); Chris@0: } Chris@0: Chris@0: $this->usages[] = $usage; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns alternative usages of the command. Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public function getUsages() Chris@0: { Chris@0: return $this->usages; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a helper instance by name. Chris@0: * Chris@0: * @param string $name The helper name Chris@0: * Chris@0: * @return mixed The helper value Chris@0: * Chris@0: * @throws LogicException if no HelperSet is defined Chris@0: * @throws InvalidArgumentException if the helper is not defined Chris@0: */ Chris@0: public function getHelper($name) Chris@0: { Chris@0: if (null === $this->helperSet) { Chris@0: 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)); Chris@0: } Chris@0: Chris@0: return $this->helperSet->get($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Validates a command name. Chris@0: * Chris@0: * It must be non-empty and parts can optionally be separated by ":". Chris@0: * Chris@0: * @param string $name Chris@0: * Chris@0: * @throws InvalidArgumentException When the name is invalid Chris@0: */ Chris@0: private function validateName($name) Chris@0: { Chris@0: if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) { Chris@0: throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name)); Chris@0: } Chris@0: } Chris@0: }