bindAPI/src/Controller/Commands/CommandGroupContainer.php

88 lines
2.5 KiB
PHP

<?php
namespace App\Controller\Commands;
use App\Utilities\Colors;
/**
*
*/
class CommandGroupContainer
{
private array $commandGroups = [];
public function addCommandGroup(CommandGroup $commandGroup): CommandGroupContainer
{
$this->commandGroups[] = $commandGroup;
return $this;
}
/**
* @return void
*/
public function printCommands(): void
{
$longestCommandLength = $this->getLongestCommandLength();
foreach ($this->commandGroups as $commandGroup) {
$commandGroup->printCommands($longestCommandLength);
}
}
/**
* @return int
*/
public function getLongestCommandLength(): int
{
$longest = 0;
foreach ($this->commandGroups as $group) {
$len = strlen(string: $group->getName());
if ($len > $longest) {
$longest = $len;
}
}
return $longest;
}
private function findGroupByName(string $command): ?CommandGroup
{
foreach ($this->commandGroups as $group) {
if ($group->getName() === $command) {
return $group;
}
}
return null;
}
public function run(string $command, string $subcommand): void
{
if ($subcommand !== '') {
if ($group = $this->findGroupByName(command: $command)) {
if ($group->exec(subcommand: $subcommand)) {
exit(0);
} else {
echo Colors::DEFAULT . 'Unknown subcommand ' . Colors::YELLOW . $subcommand . Colors::DEFAULT .' for ' . Colors::YELLOW . $command . Colors::DEFAULT . '.' . PHP_EOL;
exit(1);
}
} else {
echo Colors::DEFAULT . 'Unknown command group ' . Colors::YELLOW . $command . Colors::DEFAULT . '.' . PHP_EOL;
exit(1);
}
} else {
// check for command group and print available commands
foreach ($this->commandGroups as $group) {
if ($group->getName() === $command) {
echo 'Available subcommands for: ' . Colors::YELLOW . $group->getName() . Colors::DEFAULT . ':' . PHP_EOL;
$group->printCommands(strlen(string: $group->getName()));
exit(0);
}
}
}
echo Colors::DEFAULT . 'Unknown command ' . Colors::YELLOW . $command . Colors::DEFAULT . '.' . PHP_EOL;
}
}