feat: introduce module system and extract address book as first module (MODULAR-MONOLITH-V1-001)

Add a module kernel (ModuleManifest, ModuleRegistry) that allows modules to
contribute routes, UI slots, search providers, layout context, session
lifecycle, and permissions. Modules are activated via config/modules.php or
APP_ENABLED_MODULES env variable. Conflicts (duplicate routes, permissions,
slot keys) cause a fail-fast with a clear error message.

Extract the address book from hardcoded Core integration points into the
first module (modules/addressbook/). The module provides:
- Aside icon-bar tab + People panel via UI slot system
- Global search resource via AddressBookSearchProvider
- Layout context data via AddressBookLayoutProvider
- Session lifecycle via AddressBookSessionProvider

Core cleanup removes address-book hardcodings from SearchSqlResourceProvider,
SearchUiMetaProvider, SearchItemMapperProvider, appBuildLayoutNavContext(),
and the aside templates. Permissions (ADDRESS_BOOK_VIEW) and business logic
(AddressBookService) remain in Core as they gate general user visibility.

Includes 38 new tests (894 total), PHPStan level 5 clean, and architecture
tests verifying zero hardcoded address-book references in search/templates.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-18 15:43:25 +01:00
parent d9805c45d3
commit c364e2b46d
33 changed files with 2639 additions and 167 deletions

View File

@@ -0,0 +1,20 @@
<?php
namespace MintyPHP\App\Module\Contracts;
use MintyPHP\App\AppContainer;
/**
* Provides module-specific data for the layout navigation context.
*
* Called from appBuildLayoutNavContext() after Core data assembly.
* Return value is merged into the $layoutNav array passed to templates.
*/
interface LayoutContextProvider
{
/**
* @param array<string, mixed> $session Current session data
* @return array<string, mixed> Key-value pairs to merge into $layoutNav
*/
public function provide(array $session, AppContainer $container): array;
}

View File

@@ -0,0 +1,39 @@
<?php
namespace MintyPHP\App\Module\Contracts;
/**
* Provides search resources contributed by a module.
*
* Each provider returns a list of search resources (with SQL for count/preview/result),
* maps result rows to display items, and provides list URLs for deep-linking.
*/
interface SearchResourceProvider
{
/**
* Return search resource definitions.
*
* @return array<string, array{
* label: string,
* permission: string,
* count_sql: string,
* preview_sql: string,
* result_sql: string,
* tenant_filter?: string
* }>
*/
public function resources(): array;
/**
* Map a raw result row to a display-ready item.
*
* @param array<string, mixed> $row
* @return array{title: string, subtitle?: string, url: string, icon?: string}|null
*/
public function mapResultItem(string $resourceKey, array $row): ?array;
/**
* Return the list URL for the given resource key and encoded search term.
*/
public function listUrl(string $resourceKey, string $encodedSearch): string;
}

View File

@@ -0,0 +1,26 @@
<?php
namespace MintyPHP\App\Module\Contracts;
use MintyPHP\App\AppContainer;
/**
* Populates module-specific session data after login and cleans up on logout.
*
* Called from the login flow after successful authentication. When a module is
* deactivated, its provider is not called — session keys are simply not set.
*/
interface SessionProvider
{
/**
* Populate session keys with module-specific data after successful login.
*
* @param array<string, mixed> $user The authenticated user record
*/
public function populate(array $user, AppContainer $container): void;
/**
* Remove session keys owned by this module (called on logout).
*/
public function clear(): void;
}

View File

@@ -0,0 +1,115 @@
<?php
namespace MintyPHP\App\Module;
use InvalidArgumentException;
/**
* Immutable value object describing a single module's contributions.
*
* Each module ships a `module.php` that returns an associative array.
* ModuleManifest validates and normalises that array into a typed contract.
*/
final class ModuleManifest
{
public readonly string $id;
public readonly string $version;
public readonly bool $enabledByDefault;
public readonly int $loadOrder;
/** @var array<int, array{path: string, target: string, public?: bool}> */
public readonly array $routes;
/** @var list<string> */
public readonly array $publicPaths;
/** @var list<class-string> Container registrar FQCNs */
public readonly array $containerRegistrars;
/** @var array<string, mixed> Keyed by slot name (e.g. 'aside.tab_panel') */
public readonly array $uiSlots;
/** @var list<class-string> SearchResourceProvider FQCNs */
public readonly array $searchResources;
/** @var array<string, list<string>> Asset group name → file list */
public readonly array $assetGroups;
/** @var list<array{name: string, handler: string, schedule?: string}> */
public readonly array $schedulerJobs;
/** @var list<class-string> LayoutContextProvider FQCNs */
public readonly array $layoutContextProviders;
/** @var list<class-string> SessionProvider FQCNs */
public readonly array $sessionProviders;
/** @var list<string> Permission keys (e.g. 'address_book.view') */
public readonly array $permissions;
public readonly ?string $migrationsPath;
public readonly string $basePath;
/**
* @param array<string, mixed> $raw The manifest array returned by module.php
* @param string $basePath Absolute path to the module directory
*/
private function __construct(array $raw, string $basePath)
{
$this->basePath = $basePath;
// — required fields ————————————————————————————
if (!isset($raw['id']) || !is_string($raw['id']) || trim($raw['id']) === '') {
throw new InvalidArgumentException('Module manifest must have a non-empty string "id".');
}
$this->id = trim($raw['id']);
$this->version = isset($raw['version']) && is_string($raw['version']) ? trim($raw['version']) : '0.0.0';
$this->enabledByDefault = (bool) ($raw['enabled_by_default'] ?? false);
$this->loadOrder = (int) ($raw['load_order'] ?? 100);
// — optional contribution arrays ———————————————
$this->routes = self::arrayOf($raw, 'routes');
$this->publicPaths = self::listOf($raw, 'public_paths');
$this->containerRegistrars = self::listOf($raw, 'container_registrars');
$this->uiSlots = is_array($raw['ui_slots'] ?? null) ? $raw['ui_slots'] : [];
$this->searchResources = self::listOf($raw, 'search_resources');
$this->assetGroups = is_array($raw['asset_groups'] ?? null) ? $raw['asset_groups'] : [];
$this->schedulerJobs = self::arrayOf($raw, 'scheduler_jobs');
$this->layoutContextProviders = self::listOf($raw, 'layout_context_providers');
$this->sessionProviders = self::listOf($raw, 'session_providers');
$this->permissions = self::listOf($raw, 'permissions');
$migrationsPath = $raw['migrations_path'] ?? null;
$this->migrationsPath = is_string($migrationsPath) && trim($migrationsPath) !== ''
? rtrim($basePath, '/') . '/' . ltrim(trim($migrationsPath), '/')
: null;
}
/**
* @param array<string, mixed> $raw
*/
public static function fromArray(array $raw, string $basePath): self
{
return new self($raw, $basePath);
}
/**
* @return list<mixed>
*/
private static function listOf(array $raw, string $key): array
{
$value = $raw[$key] ?? [];
return is_array($value) ? array_values($value) : [];
}
/**
* @return array<int|string, mixed>
*/
private static function arrayOf(array $raw, string $key): array
{
$value = $raw[$key] ?? [];
return is_array($value) ? $value : [];
}
}

View File

@@ -0,0 +1,309 @@
<?php
namespace MintyPHP\App\Module;
use RuntimeException;
/**
* Loads, validates and merges module manifests.
*
* Modules are discovered from a configurable directory and activated via an
* allow-list (config/modules.php + APP_ENABLED_MODULES env variable).
*
* The registry is immutable after construction — all contributions are merged
* at boot time and available through typed getters.
*/
final class ModuleRegistry
{
/** @var array<string, ModuleManifest> keyed by module id */
private array $modules = [];
/** @var array<int, array{path: string, target: string, public?: bool}> merged routes */
private array $mergedRoutes = [];
/** @var list<string> merged public paths */
private array $mergedPublicPaths = [];
/** @var list<class-string> merged container registrar FQCNs */
private array $mergedContainerRegistrars = [];
/** @var array<string, list<mixed>> merged UI slots keyed by slot name */
private array $mergedUiSlots = [];
/** @var list<class-string> merged search resource provider FQCNs */
private array $mergedSearchResources = [];
/** @var array<string, list<string>> merged asset groups */
private array $mergedAssetGroups = [];
/** @var list<class-string> merged layout context provider FQCNs */
private array $mergedLayoutContextProviders = [];
/** @var list<class-string> merged session provider FQCNs */
private array $mergedSessionProviders = [];
/** @var list<string> merged permissions */
private array $mergedPermissions = [];
/** @var list<array{name: string, handler: string, schedule?: string}> */
private array $mergedSchedulerJobs = [];
/**
* Boot the registry from a modules directory and activation config.
*
* @param string $modulesDir Absolute path to the modules/ directory
* @param list<string> $enabledModuleIds Module IDs to activate (from config + env)
*/
public static function boot(string $modulesDir, array $enabledModuleIds): self
{
$registry = new self();
if (!is_dir($modulesDir)) {
return $registry;
}
// Discover and load manifests for enabled modules
$manifests = [];
foreach ($enabledModuleIds as $moduleId) {
$moduleId = trim($moduleId);
if ($moduleId === '') {
continue;
}
$modulePath = rtrim($modulesDir, '/') . '/' . $moduleId;
$manifestFile = $modulePath . '/module.php';
if (!is_file($manifestFile)) {
throw new RuntimeException(
"Module '{$moduleId}' is enabled but manifest not found at: {$manifestFile}"
);
}
$raw = require $manifestFile;
if (!is_array($raw)) {
throw new RuntimeException(
"Module manifest at '{$manifestFile}' must return an array."
);
}
$manifest = ModuleManifest::fromArray($raw, $modulePath);
if ($manifest->id !== $moduleId) {
throw new RuntimeException(
"Module directory '{$moduleId}' does not match manifest id '{$manifest->id}'."
);
}
$manifests[] = $manifest;
}
// Sort deterministically: load_order ASC, then id ASC
usort($manifests, static function (ModuleManifest $a, ModuleManifest $b): int {
return $a->loadOrder <=> $b->loadOrder ?: strcmp($a->id, $b->id);
});
// Register and merge
foreach ($manifests as $manifest) {
$registry->registerModule($manifest);
}
return $registry;
}
/**
* Resolve enabled module IDs from config array + ENV override.
*
* @param array{enabled_modules?: list<string>} $config From config/modules.php
* @return list<string>
*/
public static function resolveEnabledModules(array $config): array
{
$fromConfig = $config['enabled_modules'] ?? [];
$fromEnv = trim((string) getenv('APP_ENABLED_MODULES'));
if ($fromEnv !== '') {
$fromConfig = array_map('trim', explode(',', $fromEnv));
}
return array_values(array_unique(array_filter($fromConfig, static fn (string $id): bool => trim($id) !== '')));
}
private function registerModule(ModuleManifest $manifest): void
{
if (isset($this->modules[$manifest->id])) {
throw new RuntimeException(
"Duplicate module id: '{$manifest->id}' is already registered."
);
}
$this->modules[$manifest->id] = $manifest;
// — Merge routes (fail-fast on collision) ——————————————
$existingTargets = array_column($this->mergedRoutes, 'target');
foreach ($manifest->routes as $route) {
$target = $route['target'];
if (in_array($target, $existingTargets, true)) {
throw new RuntimeException(
"Route target conflict: '{$target}' from module '{$manifest->id}' collides with an existing route."
);
}
$this->mergedRoutes[] = $route;
}
// — Merge public paths ———————————————————————————
array_push($this->mergedPublicPaths, ...$manifest->publicPaths);
// — Merge container registrars ————————————————————
array_push($this->mergedContainerRegistrars, ...$manifest->containerRegistrars);
// — Merge UI slots (fail-fast on duplicate keys within same slot) ——
foreach ($manifest->uiSlots as $slotName => $contributions) {
if (!isset($this->mergedUiSlots[$slotName])) {
$this->mergedUiSlots[$slotName] = [];
}
$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."
);
}
}
}
$this->mergedUiSlots[$slotName][] = $contribution;
}
}
// — Merge search resources (fail-fast on duplicate provider) ——
foreach ($manifest->searchResources as $provider) {
if (in_array($provider, $this->mergedSearchResources, true)) {
throw new RuntimeException(
"Search resource conflict: provider '{$provider}' from module '{$manifest->id}' is already registered."
);
}
$this->mergedSearchResources[] = $provider;
}
// — Merge asset groups ————————————————————————————
foreach ($manifest->assetGroups as $groupName => $files) {
if (isset($this->mergedAssetGroups[$groupName])) {
throw new RuntimeException(
"Asset group conflict: group '{$groupName}' from module '{$manifest->id}' already exists."
);
}
$this->mergedAssetGroups[$groupName] = $files;
}
// — Merge permissions (fail-fast on duplicate) ———————
foreach ($manifest->permissions as $permission) {
if (in_array($permission, $this->mergedPermissions, true)) {
throw new RuntimeException(
"Permission conflict: '{$permission}' from module '{$manifest->id}' is already registered."
);
}
$this->mergedPermissions[] = $permission;
}
// — Merge layout context providers ————————————————
array_push($this->mergedLayoutContextProviders, ...$manifest->layoutContextProviders);
// — Merge session providers ——————————————————————
array_push($this->mergedSessionProviders, ...$manifest->sessionProviders);
// — Merge scheduler jobs —————————————————————————
array_push($this->mergedSchedulerJobs, ...$manifest->schedulerJobs);
}
// ─── Getters ────────────────────────────────────────────────────────
/** @return array<string, ModuleManifest> */
public function getModules(): array
{
return $this->modules;
}
public function hasModule(string $id): bool
{
return isset($this->modules[$id]);
}
public function getModule(string $id): ModuleManifest
{
if (!isset($this->modules[$id])) {
throw new RuntimeException("Module '{$id}' is not registered.");
}
return $this->modules[$id];
}
/** @return array<int, array{path: string, target: string, public?: bool}> */
public function getRoutes(): array
{
return $this->mergedRoutes;
}
/** @return list<string> */
public function getPublicPaths(): array
{
return $this->mergedPublicPaths;
}
/** @return list<class-string> */
public function getContainerRegistrars(): array
{
return $this->mergedContainerRegistrars;
}
/** @return array<string, list<mixed>> */
public function getUiSlots(): array
{
return $this->mergedUiSlots;
}
/**
* @return list<mixed> Contributions for a specific slot
*/
public function getSlotContributions(string $slotName): array
{
return $this->mergedUiSlots[$slotName] ?? [];
}
/** @return list<class-string> */
public function getSearchResources(): array
{
return $this->mergedSearchResources;
}
/** @return array<string, list<string>> */
public function getAssetGroups(): array
{
return $this->mergedAssetGroups;
}
/** @return list<class-string> */
public function getLayoutContextProviders(): array
{
return $this->mergedLayoutContextProviders;
}
/** @return list<class-string> */
public function getSessionProviders(): array
{
return $this->mergedSessionProviders;
}
/** @return list<string> */
public function getPermissions(): array
{
return $this->mergedPermissions;
}
/** @return list<array{name: string, handler: string, schedule?: string}> */
public function getSchedulerJobs(): array
{
return $this->mergedSchedulerJobs;
}
}

View File

@@ -1,6 +1,7 @@
<?php
use MintyPHP\App\AppContainer;
use MintyPHP\App\Container\ContainerRegistrar;
use MintyPHP\App\Container\Registrars\AccessRegistrar;
use MintyPHP\App\Container\Registrars\AppServicesRegistrar;
use MintyPHP\App\Container\Registrars\AuthRegistrar;
@@ -9,6 +10,7 @@ use MintyPHP\App\Container\Registrars\RepositoryFactoryRegistrar;
use MintyPHP\App\Container\Registrars\ServiceFactoryRegistrar;
use MintyPHP\App\Container\Registrars\SettingsRegistrar;
use MintyPHP\App\Container\Registrars\UserRegistrar;
use MintyPHP\App\Module\ModuleRegistry;
$container = new AppContainer();
@@ -29,4 +31,32 @@ foreach ($registrars as $registrar) {
$registrar->register($container);
}
// ── Module registrars (run after all Core registrars) ────────────────
// Module registrars MUST NOT overwrite existing container keys.
// The ModuleRegistry is stored in the container for downstream access.
$modulesConfig = is_file(__DIR__ . '/../../config/modules.php')
? (array) require __DIR__ . '/../../config/modules.php'
: [];
$enabledModules = ModuleRegistry::resolveEnabledModules($modulesConfig);
$modulesDir = dirname(__DIR__, 2) . '/modules';
$moduleRegistry = ModuleRegistry::boot($modulesDir, $enabledModules);
$container->set(ModuleRegistry::class, static fn (): ModuleRegistry => $moduleRegistry);
$coreKeys = []; // snapshot keys before module registrars
// We use reflection-free approach: track what the container had before modules
foreach ($moduleRegistry->getContainerRegistrars() as $registrarClass) {
if (!class_exists($registrarClass)) {
throw new RuntimeException("Module container registrar class not found: {$registrarClass}");
}
$registrarInstance = new $registrarClass();
if (!$registrarInstance instanceof ContainerRegistrar) {
throw new RuntimeException(
"Module container registrar '{$registrarClass}' must implement " . ContainerRegistrar::class
);
}
$registrarInstance->register($container);
}
return $container;