/** * Compiles arguments in a command * * @param ICommand $command The command to compile * @param IRequest $request The user request * @throws RuntimeException Thrown if there are too many arguments */ protected function compileArguments(ICommand &$command, IRequest $request) { $argumentValues = $request->getArgumentValues(); $commandArguments = $command->getArguments(); if ($this->hasTooManyArguments($argumentValues, $commandArguments)) { throw new RuntimeException("Too many arguments"); } $hasSetArrayArgument = false; foreach ($commandArguments as $argument) { if (count($argumentValues) == 0) { if (!$argument->isOptional()) { throw new RuntimeException("Argument \"{$argument->getName()}\" does not have default value"); } $command->setArgumentValue($argument->getName(), $argument->getDefaultValue()); } else { if ($hasSetArrayArgument) { throw new RuntimeException("Array argument must appear at end of list of arguments"); } if ($argument->isArray()) { // Add the rest of the values in the request to this argument $restOfArgumentValues = []; while (count($argumentValues) > 0) { $restOfArgumentValues[] = array_shift($argumentValues); } $command->setArgumentValue($argument->getName(), $restOfArgumentValues); $hasSetArrayArgument = true; } else { $command->setArgumentValue($argument->getName(), array_shift($argumentValues)); } } } }
/** * 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); }