/** * Compiles options in a command * * @param ICommand $command The command to compile * @param IRequest $request The user request */ protected function compileOptions(ICommand &$command, IRequest $request) { foreach ($command->getOptions() as $option) { $shortNameIsSet = $request->optionIsSet($option->getShortName()); $longNameIsSet = $request->optionIsSet($option->getName()); // All options are optional (duh) if ($shortNameIsSet || $longNameIsSet) { if ($longNameIsSet) { $value = $request->getOptionValue($option->getName()); } else { $value = $request->getOptionValue($option->getShortName()); } if (!$option->valueIsPermitted() && $value !== null) { throw new RuntimeException("Option \"{$option->getName()}\" does not permit a value"); } if ($option->valueIsRequired() && $value === null) { throw new RuntimeException("Option \"{$option->getName()}\" requires a value"); } if ($option->valueIsOptional() && $value == null) { $value = $option->getDefaultValue(); } $command->setOptionValue($option->getName(), $value); } } }
/** * Adds a command * * @param ICommand $command The command to add * @param bool $overwrite True if we will overwrite a command with the same name if it already exists * @throws InvalidArgumentException Thrown if a command with the input name already exists */ public function add(ICommand $command, $overwrite = false) { if (!$overwrite && $this->has($command->getName())) { throw new InvalidArgumentException("A command with name \"{$command->getName()}\" already exists"); } $command->setCommandCollection($this); $this->commands[$command->getName()] = $command; }
/** * Gets the command as text * * @param ICommand $command The command to convert * @return string The command as text */ public function format(ICommand $command) { $text = $command->getName() . " "; // Output the options foreach ($command->getOptions() as $option) { $text .= $this->formatOption($option) . " "; } /** @var Argument[] $requiredArguments */ $requiredArguments = []; /** @var Argument[] $optionalArguments */ $optionalArguments = []; /** @var Argument $arrayArgument */ $arrayArgument = null; // Categorize each argument foreach ($command->getArguments() as $argument) { if ($argument->isRequired() && !$argument->isArray()) { $requiredArguments[] = $argument; } elseif ($argument->isOptional() && !$argument->isArray()) { $optionalArguments[] = $argument; } if ($argument->isArray()) { $arrayArgument = $argument; } } // Output the required arguments foreach ($requiredArguments as $argument) { $text .= $argument->getName() . " "; } // Output the optional arguments foreach ($optionalArguments as $argument) { $text .= "[{$argument->getName()}] "; } // Output the array argument if ($arrayArgument !== null) { $text .= $this->formatArrayArgument($arrayArgument); } return trim($text); }