bindAPI/src/Controller/Commands/CommandGroup.php

68 lines
1.9 KiB
PHP

<?php
namespace App\Controller\Commands;
/**
*
*/
class CommandGroup
{
private array $commands = [];
public function __construct(private readonly string $name, private readonly string $description)
{
// no body
}
public function addCommand(Command $command): ?CommandGroup
{
$this->commands[] = $command;
return $this;
}
public function getName(): string
{
return $this->name;
}
public function printCommands(int $longestCommandLength): void
{
echo COLOR_YELLOW . str_pad(string: $this->name, length: $longestCommandLength + 1) . COLOR_WHITE . $this->description . COLOR_DEFAULT . PHP_EOL;
foreach ($this->commands as $command) {
echo COLOR_GREEN . str_pad(string: ' ', length: $longestCommandLength + 1, pad_type: STR_PAD_LEFT) . $this->name . ':' . $command->getName();
foreach ($command->getMandatoryParameters() as $optionals) {
echo ' <' . $optionals . '>';
}
foreach ($command->getOptionalParameters() as $mandatory) {
echo ' {' . $mandatory . '}';
}
echo COLOR_WHITE . ' ' . $command->getDescription();
echo COLOR_DEFAULT . PHP_EOL;
}
}
public function findCommandByName(string $command): ?Command
{
foreach ($this->commands as $currentCommand) {
if ($command === $currentCommand->getName()) {
return $currentCommand;
}
}
return null;
}
public function exec(string $subcommand): void
{
if ($command = $this->findCommandByName(command: $subcommand)) {
$command->exec();
} else {
echo COLOR_DEFAULT . 'Command ' . COLOR_YELLOW . $this->name . ':' . $subcommand . COLOR_DEFAULT . ' not found.' . PHP_EOL;
exit(1);
}
}
}