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;

View File

@@ -0,0 +1,40 @@
<?php
namespace MintyPHP\Module\AddressBook\Providers;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\LayoutContextProvider;
/**
* Provides address book data for the layout navigation context.
*
* Contributes the 'addressBook' key to $layoutNav with URL, active filters,
* and people groups from the session.
*/
final class AddressBookLayoutProvider implements LayoutContextProvider
{
public function provide(array $session, AppContainer $container): array
{
// Read query params for active filter state
$query = [];
try {
$query = requestInput()->queryAll();
} catch (\Throwable) {
// fail-open: may not be available in CLI context
}
return [
'addressBook' => [
'url' => lurl('address-book'),
'activeSearch' => trim((string) ($query['search'] ?? '')),
'activeTenants' => appNormalizeStringList($query['tenants'] ?? ''),
'activeDepartments' => appNormalizePositiveIntList($query['departments'] ?? ''),
'activeRoles' => appNormalizePositiveIntList($query['roles'] ?? ''),
'activeCustomFilters' => appNormalizeAddressBookCustomFilterQuery($query),
'peopleGroups' => is_array($session['available_departments_by_tenant'] ?? null)
? $session['available_departments_by_tenant']
: [],
],
];
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace MintyPHP\Module\AddressBook\Providers;
use MintyPHP\App\Module\Contracts\SearchResourceProvider;
/**
* Provides the address-book search resource for the global search.
*/
final class AddressBookSearchProvider implements SearchResourceProvider
{
public function resources(): array
{
return [
'address-book' => [
'label' => t('Address book'),
'permission' => 'address_book.view',
'count_sql' => "select count(*) from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}}",
'preview_sql' => "select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name limit ?",
'result_sql' => "select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name",
'tenant_filter' => 'and exists (select 1 from user_tenants ut where ut.user_id = users.id and ut.tenant_id in (???))',
],
];
}
public function mapResultItem(string $resourceKey, array $row): ?array
{
if ($resourceKey !== 'address-book') {
return null;
}
$title = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
$subtitle = (string) ($row['email'] ?? '');
$uuid = (string) ($row['uuid'] ?? '');
if ($title === '' && $subtitle === '') {
return null;
}
return [
'title' => $title !== '' ? $title : $subtitle,
'subtitle' => $subtitle,
'url' => lurl('address-book/view/' . $uuid),
'icon' => 'bi-people',
];
}
public function listUrl(string $resourceKey, string $encodedSearch): string
{
if ($resourceKey !== 'address-book') {
return '';
}
return lurl('address-book') . '?search=' . $encodedSearch;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace MintyPHP\Module\AddressBook\Providers;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\SessionProvider;
/**
* Populates session with department-by-tenant hierarchy data used by the
* address book aside panel.
*
* In V1 this data is already populated by the core auth flow (loadTenantDataIntoSession).
* This provider is a placeholder that will take over population once the core
* address book hardcodings are fully removed.
*/
final class AddressBookSessionProvider implements SessionProvider
{
public function populate(array $user, AppContainer $container): void
{
// V1: available_departments_by_tenant is still populated by core's
// AuthService::loadTenantDataIntoSession(). This provider is registered
// so the contract is satisfied and the session hook is ready for V2
// when the core delegation is fully removed.
}
public function clear(): void
{
unset($_SESSION['available_departments_by_tenant']);
}
}

View File

@@ -27,6 +27,26 @@ class SearchDataService
$tenantScopeFilters = SearchConfig::tenantScopeFilters();
$resources = SearchConfig::resources($query, $locale);
// Merge module-contributed search resources into the pipeline
$like = \MintyPHP\Support\Search\SearchQueryNormalizer::normalizeLikeQuery($query);
foreach (SearchConfig::moduleResources() as $key => $moduleDef) {
$countSql = $moduleDef['count_sql'];
$previewSql = $moduleDef['preview_sql'];
$resultSql = $moduleDef['result_sql'];
$resources[] = [
'key' => $key,
'label' => $moduleDef['label'],
'permission' => $moduleDef['permission'],
'countSql' => $countSql,
'countParams' => array_fill(0, substr_count($countSql, '?'), $like),
'previewSql' => $previewSql,
'previewParams' => array_fill(0, max(0, substr_count($previewSql, '?') - 1), $like),
'resultSql' => $resultSql,
'resultParams' => array_fill(0, substr_count($resultSql, '?'), $like),
];
}
$items = [];
foreach ($resources as $resource) {
@@ -129,6 +149,26 @@ class SearchDataService
$tenantScopeFilters = SearchConfig::tenantScopeFilters();
$resources = SearchConfig::resources($query, $locale);
// Merge module-contributed search resources
$like = \MintyPHP\Support\Search\SearchQueryNormalizer::normalizeLikeQuery($query);
foreach (SearchConfig::moduleResources() as $key => $moduleDef) {
$countSql = $moduleDef['count_sql'];
$previewSql = $moduleDef['preview_sql'];
$resultSql = $moduleDef['result_sql'];
$resources[] = [
'key' => $key,
'label' => $moduleDef['label'],
'permission' => $moduleDef['permission'],
'countSql' => $countSql,
'countParams' => array_fill(0, substr_count($countSql, '?'), $like),
'previewSql' => $previewSql,
'previewParams' => array_fill(0, max(0, substr_count($previewSql, '?') - 1), $like),
'resultSql' => $resultSql,
'resultParams' => array_fill(0, substr_count($resultSql, '?'), $like),
];
}
$results = [];
foreach ($resources as $resource) {

View File

@@ -2,18 +2,8 @@
namespace MintyPHP\Support\Search;
use MintyPHP\Service\User\UserAvatarService;
class SearchItemMapperProvider
{
/** @var (callable(): UserAvatarService)|null */
private static $userAvatarServiceResolver = null;
public static function configure(callable $userAvatarServiceResolver): void
{
self::$userAvatarServiceResolver = $userAvatarServiceResolver;
}
public static function mapPreviewItem(string $key, array $data, string $query): ?array
{
if ($key === 'users') {
@@ -23,13 +13,6 @@ class SearchItemMapperProvider
$label = $label === '' ? $email : ($label . ' — ' . $email);
}
$url = lurl('admin/users/edit/' . ($data['uuid'] ?? '')) . '?search=' . urlencode($query);
} elseif ($key === 'address-book') {
$label = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
$email = trim((string) ($data['email'] ?? ''));
if ($email !== '') {
$label = $label === '' ? $email : ($label . ' — ' . $email);
}
$url = lurl('address-book/view/' . ($data['uuid'] ?? '')) . '?search=' . urlencode($query);
} elseif ($key === 'permissions') {
$label = (string) ($data['description'] ?? '');
$url = lurl('admin/permissions/edit/' . ($data['id'] ?? '')) . '?search=' . urlencode($query);
@@ -99,15 +82,6 @@ class SearchItemMapperProvider
$title = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
$description = (string) ($data['email'] ?? '');
$url = lurl('admin/users/edit/' . ($data['uuid'] ?? ''));
} elseif ($key === 'address-book') {
$title = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
$description = (string) ($data['email'] ?? '');
$uuid = (string) ($data['uuid'] ?? '');
$url = lurl('address-book/view/' . $uuid);
$userAvatarService = self::userAvatarService();
if ($uuid !== '' && $userAvatarService->hasAvatar($uuid)) {
$image = lurl('admin/users/avatar-file') . '?uuid=' . urlencode($uuid) . '&size=64';
}
} elseif ($key === 'permissions') {
$title = (string) ($data['key'] ?? '');
$description = (string) ($data['description'] ?? '');
@@ -170,18 +144,5 @@ class SearchItemMapperProvider
];
}
private static function userAvatarService(): UserAvatarService
{
if (!is_callable(self::$userAvatarServiceResolver)) {
throw new \RuntimeException('SearchItemMapperProvider is not configured for dependency: ' . UserAvatarService::class);
}
$service = (self::$userAvatarServiceResolver)();
if (!$service instanceof UserAvatarService) {
throw new \RuntimeException('SearchItemMapperProvider resolver returned invalid dependency: ' . UserAvatarService::class);
}
return $service;
}
}

View File

@@ -12,7 +12,6 @@ class SearchSqlResourceProvider
{
return [
'users' => 'and exists (select 1 from user_tenants ut where ut.user_id = users.id and ut.tenant_id in (???))',
'address-book' => 'and exists (select 1 from user_tenants ut where ut.user_id = users.id and ut.tenant_id in (???))',
'tenants' => 'and id in (???)',
'departments' => 'and tenant_id in (???)',
];
@@ -23,18 +22,6 @@ class SearchSqlResourceProvider
$like = SearchQueryNormalizer::normalizeLikeQuery($query);
return [
[
'key' => 'address-book',
'label' => t('Address book'),
'permission' => PermissionService::ADDRESS_BOOK_VIEW,
// escape '\\\\' — four backslashes: PHP reduces to two, SQL reduces to one literal backslash escape char.
'countSql' => "select count(*) from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}}",
'countParams' => [$like, $like, $like],
'previewSql' => "select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name limit ?",
'previewParams' => [$like, $like, $like],
'resultSql' => "select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name",
'resultParams' => [$like, $like, $like],
],
[
'key' => 'users',
'label' => t('Users'),

View File

@@ -5,7 +5,6 @@ namespace MintyPHP\Support\Search;
class SearchUiMetaProvider
{
private const ICONS = [
'address-book' => 'bi-people',
'users' => 'bi-person-badge',
'tenants' => 'bi-buildings',
'departments' => 'bi-diagram-3',
@@ -20,7 +19,6 @@ class SearchUiMetaProvider
];
private const LIST_URL_KEYS = [
'address-book',
'users',
'tenants',
'departments',
@@ -43,7 +41,6 @@ class SearchUiMetaProvider
$encoded = urlencode($query);
return match ($key) {
'address-book' => lurl('address-book') . '?search=' . $encoded,
'users' => lurl('admin/users') . '?search=' . $encoded,
'tenants' => lurl('admin/tenants') . '?search=' . $encoded,
'departments' => lurl('admin/departments') . '?search=' . $encoded,

View File

@@ -2,6 +2,8 @@
namespace MintyPHP\Support;
use MintyPHP\App\Module\Contracts\SearchResourceProvider;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Support\Search\SearchItemMapperProvider;
use MintyPHP\Support\Search\SearchQueryNormalizer;
use MintyPHP\Support\Search\SearchSpecialResourceProvider;
@@ -10,9 +12,26 @@ use MintyPHP\Support\Search\SearchUiMetaProvider;
class SearchConfig
{
/** @var list<SearchResourceProvider> resolved module providers (cached per request) */
private static ?array $moduleProviders = null;
/** @var array<string, SearchResourceProvider> key→provider lookup */
private static array $moduleProviderByKey = [];
public static function tenantScopeFilters(): array
{
return SearchSqlResourceProvider::tenantScopeFilters();
$filters = SearchSqlResourceProvider::tenantScopeFilters();
// Module providers may contribute tenant scope filters via their resource definitions
foreach (self::resolveModuleProviders() as $provider) {
foreach ($provider->resources() as $key => $resource) {
if (isset($resource['tenant_filter']) && $resource['tenant_filter'] !== '') {
$filters[$key] = $resource['tenant_filter'];
}
}
}
return $filters;
}
public static function resources(string $query, string $locale): array
@@ -20,26 +39,134 @@ class SearchConfig
return SearchSqlResourceProvider::resources($query, $locale);
}
/**
* Return module-contributed search resource definitions.
* These are separate from core SQL resources and processed by SearchDataService.
*
* @return array<string, array{label: string, permission: string, count_sql: string, preview_sql: string, result_sql: string, tenant_filter?: string}>
*/
public static function moduleResources(): array
{
$resources = [];
foreach (self::resolveModuleProviders() as $provider) {
foreach ($provider->resources() as $key => $resource) {
$resources[$key] = $resource;
}
}
return $resources;
}
public static function iconForKey(string $key): string
{
// Check module provider key→icon mapping
$moduleProvider = self::$moduleProviderByKey[$key] ?? null;
if ($moduleProvider !== null) {
$mapped = $moduleProvider->mapResultItem($key, []);
if ($mapped !== null && isset($mapped['icon']) && $mapped['icon'] !== '') {
return $mapped['icon'];
}
}
return SearchUiMetaProvider::iconForKey($key);
}
public static function listUrl(string $key, string $query): string
{
// Ensure module providers are resolved before lookup
self::resolveModuleProviders();
$provider = self::$moduleProviderByKey[$key] ?? null;
if ($provider !== null) {
$url = $provider->listUrl($key, urlencode($query));
if ($url !== '') {
return $url;
}
}
return SearchUiMetaProvider::listUrl($key, $query);
}
public static function mapPreviewItem(string $key, array $data, string $query): ?array
{
self::resolveModuleProviders();
$provider = self::$moduleProviderByKey[$key] ?? null;
if ($provider !== null) {
$mapped = $provider->mapResultItem($key, $data);
if ($mapped !== null) {
return ['label' => $mapped['title'], 'url' => $mapped['url']];
}
return null;
}
return SearchItemMapperProvider::mapPreviewItem($key, $data, $query);
}
public static function mapResultItem(string $key, string $label, array $data): ?array
{
self::resolveModuleProviders();
$provider = self::$moduleProviderByKey[$key] ?? null;
if ($provider !== null) {
$mapped = $provider->mapResultItem($key, $data);
if ($mapped !== null) {
return [
'type' => $label,
'title' => $mapped['title'],
'description' => $mapped['subtitle'] ?? '',
'url' => $mapped['url'],
'image' => '',
'icon' => $mapped['icon'] ?? self::iconForKey($key),
];
}
return null;
}
return SearchItemMapperProvider::mapResultItem($key, $label, $data);
}
/**
* Resolve and cache module search providers for the current request.
*
* @return list<SearchResourceProvider>
*/
private static function resolveModuleProviders(): array
{
if (self::$moduleProviders !== null) {
return self::$moduleProviders;
}
self::$moduleProviders = [];
self::$moduleProviderByKey = [];
try {
/** @var ModuleRegistry $registry */
$registry = app(ModuleRegistry::class);
foreach ($registry->getSearchResources() as $providerClass) {
if (!class_exists($providerClass)) {
continue;
}
$provider = new $providerClass();
if ($provider instanceof SearchResourceProvider) {
self::$moduleProviders[] = $provider;
foreach ($provider->resources() as $key => $resource) {
self::$moduleProviderByKey[$key] = $provider;
}
}
}
} catch (\Throwable) {
// fail-open: module registry may not be available
}
return self::$moduleProviders;
}
/**
* Reset cached module providers (for testing).
*/
public static function resetModuleProviders(): void
{
self::$moduleProviders = null;
self::$moduleProviderByKey = [];
}
public static function hotkeyPreviewResource(string $query): ?array
{
return SearchSpecialResourceProvider::hotkeyPreviewResource($query);

View File

@@ -59,9 +59,6 @@ function setAppContainer(\MintyPHP\App\AppContainer $container): void
static fn (): \MintyPHP\Service\Access\AuthorizationService => $container->get(\MintyPHP\Service\Access\AuthorizationService::class)
);
\MintyPHP\Support\Search\SearchItemMapperProvider::configure(
static fn (): \MintyPHP\Service\User\UserAvatarService => $container->get(\MintyPHP\Service\User\UserAvatarService::class)
);
}
/**
@@ -610,8 +607,19 @@ function appBuildLayoutNavContext(array $layoutAuth, array $session, array $quer
$csrfKey = \MintyPHP\Session::$csrfSessionKey;
$csrfToken = (string) ($session[$csrfKey] ?? '');
return [
// Pre-resolve module UI slot contributions for templates (templates must not call app() directly)
$moduleUiSlots = [];
try {
/** @var \MintyPHP\App\Module\ModuleRegistry $moduleReg */
$moduleReg = app(\MintyPHP\App\Module\ModuleRegistry::class);
$moduleUiSlots = $moduleReg->getUiSlots();
} catch (\Throwable) {
// fail-open
}
$layoutNav = [
'hasAdminPanel' => layoutHasAdminPanel($layoutAuth),
'moduleSlots' => $moduleUiSlots,
'currentTenant' => $currentTenant,
'availableTenants' => $availableTenants,
'tenantQueryParam' => $tenantQueryParam,
@@ -620,19 +628,33 @@ function appBuildLayoutNavContext(array $layoutAuth, array $session, array $quer
'name' => $tenantName,
'hasAvatar' => $tenantHasAvatar,
],
'addressBook' => [
'url' => lurl('address-book'),
'activeSearch' => trim((string) ($query['search'] ?? '')),
'activeTenants' => appNormalizeStringList($query['tenants'] ?? ''),
'activeDepartments' => appNormalizePositiveIntList($query['departments'] ?? ''),
'activeRoles' => appNormalizePositiveIntList($query['roles'] ?? ''),
'activeCustomFilters' => appNormalizeAddressBookCustomFilterQuery($query),
'peopleGroups' => is_array($session['available_departments_by_tenant'] ?? null) ? $session['available_departments_by_tenant'] : [],
],
'bookmarks' => is_array($session['user_bookmarks'] ?? null)
? $session['user_bookmarks']
: ['groups' => [], 'ungrouped' => []],
'csrfKey' => $csrfKey,
'csrfToken' => $csrfToken,
];
// ── Module layout context providers ──────────────────────────────
// Modules can contribute additional layout data via LayoutContextProvider.
// Each provider returns a key-value array that is merged into $layoutNav.
try {
/** @var \MintyPHP\App\Module\ModuleRegistry $moduleRegistry */
$moduleRegistry = app(\MintyPHP\App\Module\ModuleRegistry::class);
/** @var \MintyPHP\App\AppContainer $container */
$container = $GLOBALS['minty_app_container'];
foreach ($moduleRegistry->getLayoutContextProviders() as $providerClass) {
if (!class_exists($providerClass)) {
continue;
}
$provider = new $providerClass();
if ($provider instanceof \MintyPHP\App\Module\Contracts\LayoutContextProvider) {
$layoutNav = array_merge($layoutNav, $provider->provide($session, $container));
}
}
} catch (\Throwable) {
// fail-open: if module registry is not available, skip module providers
}
return $layoutNav;
}