1
0

feat: extend module platform with UI slots, runtime components, CLI tooling and {{userId}} search support

Completes the generic module platform that enables modules to contribute
UI elements, runtime JS components, and search resources without any
core hardcoding.

New generic UI slot types:
- topbar.right_item: module-contributed topbar buttons
- layout.body_end_template: module-contributed dialog/overlay templates
- layout.head_style: module-contributed global CSS
- runtime.component: declarative JS component registration with phase ordering

New infrastructure:
- ModuleAutoloader: PSR-4 autoloading for module-local PHP classes
- ModuleRuntimePageBuilder: symlinks module pages into runtime directory
- ModuleRuntimeAssetPublisher: publishes module CSS/JS to web/modules/
- ModulePermissionSynchronizer: syncs module permissions to DB
- CLI scripts: module-runtime-sync, module-build, module-migrate,
  module-permissions-sync, module-assets-sync
- {{userId}} placeholder in SearchDataService for user-scoped search queries
- Component runtime with phased initialization (early/default/late)
- AppContainer.protectExistingBindings() to prevent module→core overwrites
- Architecture tests: ModuleStructureContractTest, CoreTemplateIsolationTest,
  FrontendComponentRuntimeContractTest, AppContainerIsolationContractTest

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-18 22:19:56 +01:00
parent c364e2b46d
commit c7b8fd516a
139 changed files with 7591 additions and 2535 deletions

View File

@@ -15,10 +15,21 @@ use RuntimeException;
*/
final class ModuleRegistry
{
/** @var array<string, list<string>> */
private const UI_SLOT_REQUIRED_KEYS = [
'aside.tab_panel' => ['key', 'label', 'icon', 'permission', 'panel_template'],
'search.resource_item' => ['key', 'label', 'base_url', 'permission'],
'user.edit.aside_action' => ['key', 'type', 'label', 'permission'],
'topbar.right_item' => ['key', 'template'],
'layout.body_end_template' => ['key', 'template'],
'layout.head_style' => ['key', 'path'],
'runtime.component' => ['key', 'script'],
];
/** @var array<string, ModuleManifest> keyed by module id */
private array $modules = [];
/** @var array<int, array{path: string, target: string, public?: bool}> merged routes */
/** @var array<int, array{path: string, target: string, module_id: string, public?: bool}> merged routes */
private array $mergedRoutes = [];
/** @var list<string> merged public paths */
@@ -42,12 +53,53 @@ final class ModuleRegistry
/** @var list<class-string> merged session provider FQCNs */
private array $mergedSessionProviders = [];
/** @var list<string> merged permissions */
/**
* @var list<array{
* key: string,
* description: string,
* active: int,
* is_system: int
* }> merged permissions
*/
private array $mergedPermissions = [];
/** @var list<array{name: string, handler: string, schedule?: string}> */
/** @var list<class-string> merged authorization policy FQCNs */
private array $mergedAuthorizationPolicies = [];
/** @var array<string, string> merged layout capabilities: UI-key → ability */
private array $mergedLayoutCapabilities = [];
/**
* @var list<array{
* job_key: string,
* handler: string,
* label: string,
* description: string,
* default_enabled: int,
* default_timezone: string,
* default_schedule_type: string,
* default_schedule_interval: int,
* default_schedule_time: ?string,
* default_schedule_weekdays_csv: ?string,
* default_catchup_once: int,
* allowed_schedule_types: list<string>,
* module_id: string
* }>
*/
private array $mergedSchedulerJobs = [];
/** @var array<string, string> route target => owning module id */
private array $routeTargetOwners = [];
/** @var array<string, string> route path => owning module id */
private array $routePathOwners = [];
/** @var array<string, string> permission key => owning module id */
private array $permissionOwners = [];
/** @var array<string, string> scheduler job key => owning module id */
private array $schedulerJobOwners = [];
/**
* Boot the registry from a modules directory and activation config.
*
@@ -102,11 +154,16 @@ final class ModuleRegistry
return $a->loadOrder <=> $b->loadOrder ?: strcmp($a->id, $b->id);
});
// Allow module-local classes (modules/<id>/lib/...) to autoload.
ModuleAutoloader::register($manifests);
// Register and merge
foreach ($manifests as $manifest) {
$registry->registerModule($manifest);
}
$registry->finalizeMergedContributions();
return $registry;
}
@@ -119,10 +176,17 @@ final class ModuleRegistry
public static function resolveEnabledModules(array $config): array
{
$fromConfig = $config['enabled_modules'] ?? [];
$fromEnv = trim((string) getenv('APP_ENABLED_MODULES'));
$fromEnvRaw = getenv('APP_ENABLED_MODULES');
if ($fromEnv !== '') {
$fromConfig = array_map('trim', explode(',', $fromEnv));
// Semantics:
// - not set => use config/modules.php
// - set '' => explicit "no modules"
// - set list => exact list from env
if ($fromEnvRaw !== false) {
$fromEnv = trim((string) $fromEnvRaw);
$fromConfig = $fromEnv === ''
? []
: array_map('trim', explode(',', $fromEnv));
}
return array_values(array_unique(array_filter($fromConfig, static fn (string $id): bool => trim($id) !== '')));
@@ -139,15 +203,28 @@ final class ModuleRegistry
$this->modules[$manifest->id] = $manifest;
// — Merge routes (fail-fast on collision) ——————————————
$existingTargets = array_column($this->mergedRoutes, 'target');
foreach ($manifest->routes as $route) {
foreach ($manifest->routes as $rawRoute) {
$route = $this->normalizeRoute($rawRoute, $manifest->id);
$path = $route['path'];
$target = $route['target'];
if (in_array($target, $existingTargets, true)) {
if (isset($this->routeTargetOwners[$target]) && $this->routeTargetOwners[$target] !== $manifest->id) {
$owner = $this->routeTargetOwners[$target];
throw new RuntimeException(
"Route target conflict: '{$target}' from module '{$manifest->id}' collides with an existing route."
"Route target conflict: '{$target}' from module '{$manifest->id}' collides with module '{$owner}'."
);
}
if (isset($this->routePathOwners[$path])) {
$owner = $this->routePathOwners[$path];
throw new RuntimeException(
"Route path conflict: '{$path}' from module '{$manifest->id}' collides with module '{$owner}'."
);
}
$this->routeTargetOwners[$target] = $manifest->id;
$this->routePathOwners[$path] = $manifest->id;
$this->mergedRoutes[] = $route;
if (!empty($route['public'])) {
$this->mergedPublicPaths[] = $path;
}
}
// — Merge public paths ———————————————————————————
@@ -163,23 +240,27 @@ final class ModuleRegistry
}
$contributionList = is_array($contributions) ? $contributions : [$contributions];
foreach ($contributionList as $contribution) {
$key = is_array($contribution) ? ($contribution['key'] ?? null) : null;
if ($key !== null) {
foreach ($this->mergedUiSlots[$slotName] as $existing) {
$existingKey = is_array($existing) ? ($existing['key'] ?? null) : null;
if ($existingKey === $key) {
throw new RuntimeException(
"UI slot conflict: slot '{$slotName}' key '{$key}' from module '{$manifest->id}' already exists."
);
}
$normalizedContribution = $this->normalizeUiSlotContribution($slotName, $contribution, $manifest->id);
$key = (string) $normalizedContribution['key'];
foreach ($this->mergedUiSlots[$slotName] as $existing) {
$existingKey = is_array($existing) ? ($existing['key'] ?? null) : null;
if ($existingKey === $key) {
throw new RuntimeException(
"UI slot conflict: slot '{$slotName}' key '{$key}' from module '{$manifest->id}' already exists."
);
}
}
$this->mergedUiSlots[$slotName][] = $contribution;
$this->mergedUiSlots[$slotName][] = $normalizedContribution;
}
}
// — Merge search resources (fail-fast on duplicate provider) ——
foreach ($manifest->searchResources as $provider) {
if (!is_string($provider) || trim($provider) === '') {
throw new RuntimeException(
"Search resource provider in module '{$manifest->id}' must be a non-empty class-string."
);
}
if (in_array($provider, $this->mergedSearchResources, true)) {
throw new RuntimeException(
"Search resource conflict: provider '{$provider}' from module '{$manifest->id}' is already registered."
@@ -200,22 +281,283 @@ final class ModuleRegistry
// — Merge permissions (fail-fast on duplicate) ———————
foreach ($manifest->permissions as $permission) {
if (in_array($permission, $this->mergedPermissions, true)) {
$permissionKey = trim((string) $permission['key']);
if ($permissionKey === '') {
throw new RuntimeException(
"Permission conflict: '{$permission}' from module '{$manifest->id}' is already registered."
"Permission in module '{$manifest->id}' must define non-empty 'key'."
);
}
$this->mergedPermissions[] = $permission;
if (isset($this->permissionOwners[$permissionKey])) {
$owner = $this->permissionOwners[$permissionKey];
throw new RuntimeException(
"Permission conflict: '{$permissionKey}' from module '{$manifest->id}' is already registered by module '{$owner}'."
);
}
$this->permissionOwners[$permissionKey] = $manifest->id;
$this->mergedPermissions[] = [
'key' => $permissionKey,
'description' => trim((string) $permission['description']),
'active' => (int) $permission['active'],
'is_system' => (int) $permission['is_system'],
];
}
// — Merge layout context providers ————————————————
array_push($this->mergedLayoutContextProviders, ...$manifest->layoutContextProviders);
foreach ($manifest->layoutContextProviders as $providerClass) {
if (!is_string($providerClass) || trim($providerClass) === '') {
throw new RuntimeException(
"Layout context provider in module '{$manifest->id}' must be a non-empty class-string."
);
}
$this->mergedLayoutContextProviders[] = $providerClass;
}
// — Merge session providers ——————————————————————
array_push($this->mergedSessionProviders, ...$manifest->sessionProviders);
foreach ($manifest->sessionProviders as $providerClass) {
if (!is_string($providerClass) || trim($providerClass) === '') {
throw new RuntimeException(
"Session provider in module '{$manifest->id}' must be a non-empty class-string."
);
}
$this->mergedSessionProviders[] = $providerClass;
}
// — Merge authorization policies (fail-fast on duplicate) ———
foreach ($manifest->authorizationPolicies as $policyClass) {
if (!is_string($policyClass) || trim($policyClass) === '') {
throw new RuntimeException(
"Authorization policy in module '{$manifest->id}' must be a non-empty class-string."
);
}
if (in_array($policyClass, $this->mergedAuthorizationPolicies, true)) {
throw new RuntimeException(
"Authorization policy conflict: '{$policyClass}' from module '{$manifest->id}' is already registered."
);
}
$this->mergedAuthorizationPolicies[] = $policyClass;
}
// — Merge layout capabilities (fail-fast on duplicate key) ———
foreach ($manifest->layoutCapabilities as $uiKey => $ability) {
$uiKey = trim((string) $uiKey);
$ability = trim((string) $ability);
if ($uiKey === '' || $ability === '') {
throw new RuntimeException(
"Layout capability in module '{$manifest->id}' must have non-empty key and ability."
);
}
if (isset($this->mergedLayoutCapabilities[$uiKey])) {
throw new RuntimeException(
"Layout capability conflict: key '{$uiKey}' from module '{$manifest->id}' is already registered."
);
}
$this->mergedLayoutCapabilities[$uiKey] = $ability;
}
// — Merge scheduler jobs —————————————————————————
array_push($this->mergedSchedulerJobs, ...$manifest->schedulerJobs);
foreach ($manifest->schedulerJobs as $schedulerJob) {
$jobKey = trim((string) $schedulerJob['job_key']);
if ($jobKey === '') {
throw new RuntimeException(
"Scheduler job in module '{$manifest->id}' must define non-empty 'job_key'."
);
}
if (isset($this->schedulerJobOwners[$jobKey])) {
$owner = $this->schedulerJobOwners[$jobKey];
throw new RuntimeException(
"Scheduler job conflict: '{$jobKey}' from module '{$manifest->id}' is already registered by module '{$owner}'."
);
}
$this->schedulerJobOwners[$jobKey] = $manifest->id;
$this->mergedSchedulerJobs[] = [
'job_key' => $jobKey,
'handler' => trim((string) $schedulerJob['handler']),
'label' => trim((string) $schedulerJob['label']),
'description' => trim((string) $schedulerJob['description']),
'default_enabled' => (int) $schedulerJob['default_enabled'],
'default_timezone' => trim((string) $schedulerJob['default_timezone']),
'default_schedule_type' => trim((string) $schedulerJob['default_schedule_type']),
'default_schedule_interval' => (int) $schedulerJob['default_schedule_interval'],
'default_schedule_time' => $schedulerJob['default_schedule_time'],
'default_schedule_weekdays_csv' => $schedulerJob['default_schedule_weekdays_csv'],
'default_catchup_once' => (int) $schedulerJob['default_catchup_once'],
'allowed_schedule_types' => array_values($schedulerJob['allowed_schedule_types']),
'module_id' => $manifest->id,
];
}
}
private function finalizeMergedContributions(): void
{
$this->mergedPublicPaths = array_values(array_unique(array_filter(
$this->mergedPublicPaths,
static fn (mixed $path): bool => trim((string) $path) !== ''
)));
foreach ($this->mergedUiSlots as $slotName => $items) {
usort($items, static function (array $a, array $b): int {
$orderCmp = ((int) ($a['order'] ?? 100)) <=> ((int) ($b['order'] ?? 100));
if ($orderCmp !== 0) {
return $orderCmp;
}
$moduleCmp = strcmp((string) ($a['__module_id'] ?? ''), (string) ($b['__module_id'] ?? ''));
if ($moduleCmp !== 0) {
return $moduleCmp;
}
return strcmp((string) ($a['key'] ?? ''), (string) ($b['key'] ?? ''));
});
foreach ($items as &$item) {
unset($item['__module_id']);
}
unset($item);
$this->mergedUiSlots[$slotName] = $items;
}
}
/**
* @return array{path: string, target: string, module_id: string, public?: bool}
*/
private function normalizeRoute(mixed $rawRoute, string $moduleId): array
{
if (!is_array($rawRoute)) {
throw new RuntimeException("Route entries in module '{$moduleId}' must be arrays.");
}
$path = trim((string) ($rawRoute['path'] ?? ''));
$target = trim((string) ($rawRoute['target'] ?? ''));
if ($path === '' || $target === '') {
throw new RuntimeException("Routes in module '{$moduleId}' must define non-empty 'path' and 'target'.");
}
$normalized = [
'path' => $path,
'target' => $target,
'module_id' => $moduleId,
];
if (array_key_exists('public', $rawRoute)) {
$normalized['public'] = (bool) $rawRoute['public'];
}
return $normalized;
}
/**
* @return array<string, mixed>
*/
private function normalizeUiSlotContribution(string $slotName, mixed $rawContribution, string $moduleId): array
{
if (!is_array($rawContribution)) {
throw new RuntimeException(
"UI slot contribution for slot '{$slotName}' in module '{$moduleId}' must be an array."
);
}
$key = trim((string) ($rawContribution['key'] ?? ''));
if ($key === '') {
throw new RuntimeException(
"UI slot contribution for slot '{$slotName}' in module '{$moduleId}' must define a non-empty 'key'."
);
}
foreach (self::UI_SLOT_REQUIRED_KEYS[$slotName] ?? [] as $requiredKey) {
$requiredValue = trim((string) ($rawContribution[$requiredKey] ?? ''));
if ($requiredValue === '') {
throw new RuntimeException(
"UI slot contribution for slot '{$slotName}' in module '{$moduleId}' is missing required key '{$requiredKey}'."
);
}
}
$this->validateUiSlotContributionByType($slotName, $rawContribution, $moduleId, $key);
$normalized = $rawContribution;
$normalized['key'] = $key;
$normalized['order'] = (int) ($rawContribution['order'] ?? 100);
$normalized['__module_id'] = $moduleId;
$normalized['module_id'] = $moduleId;
return $normalized;
}
/**
* @param array<string, mixed> $rawContribution
*/
private function validateUiSlotContributionByType(
string $slotName,
array $rawContribution,
string $moduleId,
string $slotKey
): void {
if (in_array($slotName, ['aside.tab_panel', 'topbar.right_item', 'layout.body_end_template'], true)) {
$templatePath = trim((string) ($rawContribution['panel_template'] ?? $rawContribution['template'] ?? ''));
if ($templatePath === '' || !is_file($templatePath)) {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot '{$slotName}' in module '{$moduleId}' references missing template '{$templatePath}'."
);
}
}
if ($slotName === 'layout.head_style') {
$path = trim((string) ($rawContribution['path'] ?? ''));
if ($path === '' || str_contains($path, '..')) {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'layout.head_style' in module '{$moduleId}' has invalid path '{$path}'."
);
}
}
if ($slotName === 'user.edit.aside_action') {
$type = strtolower(trim((string) ($rawContribution['type'] ?? 'link')));
if ($type !== 'link' && $type !== 'form') {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'user.edit.aside_action' in module '{$moduleId}' has invalid type '{$type}'."
);
}
if ($type === 'form') {
$action = trim((string) ($rawContribution['action'] ?? ''));
if ($action === '') {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'user.edit.aside_action' in module '{$moduleId}' requires non-empty 'action' for type=form."
);
}
} else {
$href = trim((string) ($rawContribution['href'] ?? ''));
if ($href === '') {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'user.edit.aside_action' in module '{$moduleId}' requires non-empty 'href' for type=link."
);
}
}
}
if ($slotName === 'runtime.component') {
$script = trim((string) ($rawContribution['script'] ?? ''));
if ($script === '' || str_contains($script, '..')) {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'runtime.component' in module '{$moduleId}' has invalid script '{$script}'."
);
}
$phase = strtolower(trim((string) ($rawContribution['phase'] ?? 'late')));
if (!in_array($phase, ['early', 'default', 'late'], true)) {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'runtime.component' in module '{$moduleId}' has invalid phase '{$phase}'."
);
}
$configPath = trim((string) ($rawContribution['config_path'] ?? ''));
if ($configPath !== '' && !preg_match('/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)+$/', $configPath)) {
throw new RuntimeException(
"UI slot contribution '{$slotKey}' for slot 'runtime.component' in module '{$moduleId}' has invalid config_path '{$configPath}'."
);
}
}
}
// ─── Getters ────────────────────────────────────────────────────────
@@ -239,7 +581,7 @@ final class ModuleRegistry
return $this->modules[$id];
}
/** @return array<int, array{path: string, target: string, public?: bool}> */
/** @return array<int, array{path: string, target: string, module_id: string, public?: bool}> */
public function getRoutes(): array
{
return $this->mergedRoutes;
@@ -295,13 +637,52 @@ final class ModuleRegistry
return $this->mergedSessionProviders;
}
/** @return list<string> */
/**
* @return list<array{key: string, description: string, active: int, is_system: int}>
*/
public function getPermissions(): array
{
return $this->mergedPermissions;
}
/** @return list<array{name: string, handler: string, schedule?: string}> */
/** @return list<string> */
public function getPermissionKeys(): array
{
return array_values(array_map(
static fn (array $permission): string => (string) $permission['key'],
$this->mergedPermissions
));
}
/** @return list<class-string> */
public function getAuthorizationPolicies(): array
{
return $this->mergedAuthorizationPolicies;
}
/** @return array<string, string> UI-capability-key → ability-string */
public function getLayoutCapabilities(): array
{
return $this->mergedLayoutCapabilities;
}
/**
* @return list<array{
* job_key: string,
* handler: string,
* label: string,
* description: string,
* default_enabled: int,
* default_timezone: string,
* default_schedule_type: string,
* default_schedule_interval: int,
* default_schedule_time: ?string,
* default_schedule_weekdays_csv: ?string,
* default_catchup_once: int,
* allowed_schedule_types: list<string>,
* module_id: string
* }>
*/
public function getSchedulerJobs(): array
{
return $this->mergedSchedulerJobs;