First setup: module registry, switchable modules, permissions
This commit is contained in:
commit
936c794597
52 files changed
+1304
No files matched your search
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Support;
|
||||
|
||||
use IriksIT\Manager\Contracts\Module;
|
||||
use IriksIT\Manager\Exceptions\ModuleException;
|
||||
|
||||
/**
|
||||
* Knows which modules exist and which of them are on for this site.
|
||||
*/
|
||||
final class ModuleRegistry
|
||||
{
|
||||
/** @var array<string, Module> */
|
||||
private array $all = [];
|
||||
|
||||
/**
|
||||
* @param list<class-string<Module>> $available
|
||||
* @param array<string, bool> $switches
|
||||
*/
|
||||
public function __construct(array $available, private readonly array $switches)
|
||||
{
|
||||
foreach ($available as $class) {
|
||||
$module = new $class;
|
||||
$this->all[$module->key()] = $module;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, Module> every known module */
|
||||
public function all(): array
|
||||
{
|
||||
return $this->all;
|
||||
}
|
||||
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return isset($this->all[$key]);
|
||||
}
|
||||
|
||||
public function enabled(string $key): bool
|
||||
{
|
||||
if (! $this->has($key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) ($this->switches[$key] ?? $this->all[$key]->enabledByDefault());
|
||||
}
|
||||
|
||||
/** @return array<string, Module> the modules that are on */
|
||||
public function active(): array
|
||||
{
|
||||
return array_filter($this->all, fn (Module $module) => $this->enabled($module->key()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A module that is on while one it needs is off is a configuration mistake: fail loudly at boot.
|
||||
*/
|
||||
public function validate(): void
|
||||
{
|
||||
foreach ($this->active() as $module) {
|
||||
foreach ($module->requires() as $needed) {
|
||||
if (! $this->enabled($needed)) {
|
||||
throw new ModuleException("Manager module '{$module->key()}' needs module '{$needed}', which is off.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, string> permission value => label, of the active modules only */
|
||||
public function permissions(): array
|
||||
{
|
||||
$permissions = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
$permissions += $module->permissions();
|
||||
}
|
||||
|
||||
return $permissions;
|
||||
}
|
||||
|
||||
/** @return list<array{label: string, route: string, permission: string}> */
|
||||
public function navigation(): array
|
||||
{
|
||||
$items = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
array_push($items, ...$module->navigation());
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user