From 5699bc6c5b0f988848a4f7dd601614032b733ec4 Mon Sep 17 00:00:00 2001 From: fs Date: Wed, 1 Apr 2026 20:27:42 +0200 Subject: [PATCH] refactor(config): remove runtime config files and centralize route/bootstrap --- .agents/checks/guard-catalog.json | 2 +- CLAUDE.md | 7 +- config/config.php.example | 25 ---- config/router.php | 50 -------- config/settings.php | 17 --- docs/explanation-einstellungen-speicherung.md | 6 +- i18n/default_de.json | 7 +- i18n/default_en.json | 7 +- lib/Http/AccessControl.php | 13 ++- lib/Http/RouteCatalog.php | 100 ++++++++++++++++ lib/Http/RouteRegistrar.php | 56 +++++++++ lib/Service/Settings/SettingCacheService.php | 45 +++++++- .../Settings/SettingServicesFactory.php | 5 +- lib/Support/helpers/app.php | 2 +- pages/admin/settings/index(default).phtml | 2 +- .../App/Module/RouterConfigCollisionTest.php | 18 +-- tests/Architecture/ConfigContractsTest.php | 107 ++++++++++++++++++ tests/Http/RouteCatalogTest.php | 90 +++++++++++++++ .../Settings/SettingCacheServiceTest.php | 38 +++++++ web/index.php | 8 +- 20 files changed, 487 insertions(+), 118 deletions(-) delete mode 100644 config/router.php delete mode 100644 config/settings.php create mode 100644 lib/Http/RouteCatalog.php create mode 100644 lib/Http/RouteRegistrar.php create mode 100644 tests/Architecture/ConfigContractsTest.php create mode 100644 tests/Http/RouteCatalogTest.php diff --git a/.agents/checks/guard-catalog.json b/.agents/checks/guard-catalog.json index 961565c..c6e19a0 100644 --- a/.agents/checks/guard-catalog.json +++ b/.agents/checks/guard-catalog.json @@ -27,7 +27,7 @@ "area": "core", "reviewer": "code", "title": "Settings in DB, not config files", - "requirement": "New application settings MUST be stored in the settings DB table. config/settings.php is a partial hot-path cache only." + "requirement": "New application settings MUST be stored in the settings DB table. storage/runtime/settings.php is a partial hot-path cache only." }, { "id": "GR-CORE-012", diff --git a/CLAUDE.md b/CLAUDE.md index 310b6b7..a7f8341 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -77,7 +77,7 @@ templates/ # Core layouts and partials partials/ # Reusable UI components emails/ # Email HTML templates pdfs/ # PDF templates (Dompdf) -config/ # App config (routes, assets, settings cache, themes, modules) +config/ # App config (routes, assets, themes, modules) web/ # Document root (entry point, CSS, JS, static assets) js/core/ # DOM utilities, Grid.js factory, component runtime js/components/ # Reusable UI components @@ -85,6 +85,7 @@ web/ # Document root (entry point, CSS, JS, static assets) modules/ # Published module assets (symlinks to modules//web/) storage/ # Uploaded files + runtime state runtime/pages/ # Symlinked page tree (core + modules, built by module-build) + runtime/settings.php # Hot-path settings cache file (generated by SettingCacheService) db/init/init.sql # Full schema + seed data (no migration framework) db/updates/ # Idempotent SQL update scripts for existing installs tests/ # PHPUnit tests (namespace MintyPHP\Tests\) @@ -141,7 +142,7 @@ docker/ # Dockerfiles, Nginx configs, PHP configs - All user-facing text uses `t('key')` translation helper — keys must exist in all language files under `i18n/` - Request input via `requestInput()` — never raw `$_GET`/`$_POST`/`$_SESSION` (GR-CORE-003) - Permissions + tenant scope enforced in actions/services, never just in UI -- Security/integration settings stay in DB, not in `config/settings.php` file cache (GR-CORE-011) +- Security/integration settings stay in DB, not in `storage/runtime/settings.php` file cache (GR-CORE-011) - POST-Redirect-GET (PRG) pattern on form submissions; flash before redirect (GR-CORE-012) - Constructor injection for dependencies; no hidden global state (GR-TEST-002) - New/changed Service or Gateway must have PHPUnit tests — happy path + edge case (GR-TEST-001) @@ -184,7 +185,7 @@ docker/ # Dockerfiles, Nginx configs, PHP configs - Schema defined in `db/init/init.sql` (applied once on container init) - No migration framework — core schema changes for existing installs are idempotent SQL scripts in `db/updates/` - Module schema changes via `module:migrate` (separate from core) -- Settings stored in `settings` DB table (single source of truth); `config/settings.php` is a partial file cache for hot-path UI reads only +- Settings stored in `settings` DB table (single source of truth); `storage/runtime/settings.php` is a partial file cache for hot-path UI reads only ## Security (non-negotiable) diff --git a/config/config.php.example b/config/config.php.example index 0faa294..ce9b148 100644 --- a/config/config.php.example +++ b/config/config.php.example @@ -64,31 +64,6 @@ if (!defined('APP_LOCALES')) { define('APP_LOCALES', $envList('APP_LOCALES', ['de', 'en'])); } -if (!defined('APP_ROUTE_DEFINITIONS')) { - $routesFile = __DIR__ . '/routes.php'; - $routeDefinitions = is_file($routesFile) ? include $routesFile : []; - if (!is_array($routeDefinitions)) { - $routeDefinitions = []; - } - define('APP_ROUTE_DEFINITIONS', $routeDefinitions); -} - -if (!defined('APP_PUBLIC_PATHS')) { - $publicPaths = []; - foreach (APP_ROUTE_DEFINITIONS as $route) { - if (!empty($route['public'])) { - $path = trim((string) ($route['path'] ?? '')); - if ($path !== '') { - $publicPaths[] = $path; - } - } - } - if (!$publicPaths) { - throw new RuntimeException('No public routes configured in config/routes.php'); - } - define('APP_PUBLIC_PATHS', array_values(array_unique($publicPaths))); -} - date_default_timezone_set(APP_TIMEZONE); Router::$baseUrl = '/'; // default: '/' diff --git a/config/router.php b/config/router.php deleted file mode 100644 index 161335e..0000000 --- a/config/router.php +++ /dev/null @@ -1,50 +0,0 @@ -getRoutes() as $route) { - $path = trim((string) $route['path']); - $target = trim((string) $route['target']); - $moduleId = trim((string) $route['module_id']); - if ($path !== '' && $target !== '') { - if (isset($coreRoutePaths[$path])) { - throw new RuntimeException( - "Module route path conflict: '{$path}' from module '{$moduleId}' collides with core route target '{$coreRoutePaths[$path]}'." - ); - } - if (isset($modulePaths[$path])) { - throw new RuntimeException( - "Module route path conflict: '{$path}' from module '{$moduleId}' collides with module '{$modulePaths[$path]}'." - ); - } - $modulePaths[$path] = $moduleId; - Router::addRoute($path, $target); - } - } -} diff --git a/config/settings.php b/config/settings.php deleted file mode 100644 index 9b2d7c2..0000000 --- a/config/settings.php +++ /dev/null @@ -1,17 +0,0 @@ - 'CoreCore', - 'app_locale' => 'de', - 'app_theme' => 'light', - 'app_theme_user' => '1', - 'app_registration' => '1', - 'app_primary_color' => '#105433', - 'api_token_default_ttl_days' => '90', - 'api_token_max_ttl_days' => '365', - 'api_cors_allowed_origins' => 'http://localhost:8080 -http://127.0.0.1:8080', - 'frontend_telemetry_enabled' => '1', - 'frontend_telemetry_sample_rate' => '0.2', - 'frontend_telemetry_allowed_events' => 'ajax_error,warn_once', -]; diff --git a/docs/explanation-einstellungen-speicherung.md b/docs/explanation-einstellungen-speicherung.md index 73a5c30..0aa5c4a 100644 --- a/docs/explanation-einstellungen-speicherung.md +++ b/docs/explanation-einstellungen-speicherung.md @@ -5,7 +5,7 @@ Letzte Aktualisierung: 2026-03-25 ## Kurzfassung - **Source of truth ist immer die Tabelle `settings` in der Datenbank.** -- `config/settings.php` ist nur ein **Teil-Cache** für wenige, sehr häufig gelesene UI-Basiswerte. +- `storage/runtime/settings.php` ist nur ein **Teil-Cache** für wenige, sehr häufig gelesene UI-Basiswerte. - Nicht alle Settings müssen oder sollen im Datei-Cache stehen. ## Warum es beides gibt @@ -17,7 +17,7 @@ Die Kombination ist bewusst so gebaut: - Validierung und Schreiblogik laufen über domänenspezifische Gateways und `AdminSettingsService`. 2. **Datei-Cache für Hot-Path-Reads** - - `config/settings.php` wird durch `SettingCacheService` geschrieben. + - `storage/runtime/settings.php` wird durch `SettingCacheService` geschrieben. - Verwendet wird er über `appSetting(...)` nur für globale Basiswerte wie: - `app_title` - `app_locale` @@ -36,7 +36,7 @@ Sicherheits- oder Integrationswerte werden direkt aus DB gelesen, z. B.: - User-Lifecycle-Policies (`user_inactivity_deactivate_days`, `user_inactivity_delete_days`) - Scheduler-/Job-Konfiguration (`scheduled_jobs`, `scheduled_job_runs`) -Daher ist es korrekt, wenn diese Werte in `settings` (DB) vorhanden sind, aber nicht in `config/settings.php`. +Daher ist es korrekt, wenn diese Werte in `settings` (DB) vorhanden sind, aber nicht in `storage/runtime/settings.php`. ## Laufzeitfluss diff --git a/i18n/default_de.json b/i18n/default_de.json index 76f5073..d33c74d 100644 --- a/i18n/default_de.json +++ b/i18n/default_de.json @@ -98,7 +98,7 @@ "This action revokes all active API tokens immediately across all users.": "Diese Aktion widerruft sofort alle aktiven API-Tokens über alle Benutzer hinweg.", "The authority URL defines the Microsoft identity tenant endpoint used for sign-in.": "Die Authority-URL definiert den Microsoft-Identity-Tenant-Endpunkt für die Anmeldung.", "This will expire all remember-me tokens immediately and force users to sign in again.": "Dadurch werden alle Remember-me-Tokens sofort abgelaufen und Benutzer müssen sich erneut anmelden.", - "Global settings are stored in the database. config/settings.php is only a runtime cache for selected app settings.": "Globale Einstellungen werden in der Datenbank gespeichert. config/settings.php ist nur ein Laufzeit-Cache für ausgewählte App-Einstellungen.", + "Global settings are stored in the database. storage/runtime/settings.php is only a runtime cache for selected app settings.": "Globale Einstellungen werden in der Datenbank gespeichert. storage/runtime/settings.php ist nur ein Laufzeit-Cache für ausgewählte App-Einstellungen.", "Too many login attempts. Please wait and try again.": "Zu viele Login-Versuche. Bitte warte kurz und versuche es erneut.", "No login method is available for this tenant": "Für diesen Mandanten ist keine Login-Methode verfügbar", "Create your account": "Erstelle dein Konto", @@ -376,11 +376,16 @@ "Search...": "Suchen...", "To start searching, type in the search field.": "Um die Suche zu starten, gib etwas in das Suchfeld ein.", "Tip: Use {shortcut} to focus search quickly.": "Tipp: Mit {shortcut} fokussierst du die Suche schnell.", + "Search users, tenants, pages...": "Benutzer, Mandanten, Seiten durchsuchen...", + "Users, tenants, departments, roles and more": "Benutzer, Mandanten, Abteilungen, Rollen und mehr", "Searching...": "Suche läuft...", "Search failed. Please try again.": "Suche fehlgeschlagen. Bitte erneut versuchen.", "No results found": "Keine Ergebnisse gefunden", "View all results": "Alle Ergebnisse anzeigen", "to close": "zum Schließen", + "navigate": "navigieren", + "open": "öffnen", + "close": "schließen", "Created from": "Erstellt von", "Created to": "Erstellt bis", "Files": "Dateien", diff --git a/i18n/default_en.json b/i18n/default_en.json index d2487b1..c7597c6 100644 --- a/i18n/default_en.json +++ b/i18n/default_en.json @@ -100,7 +100,7 @@ "This action revokes all active API tokens immediately across all users.": "This action revokes all active API tokens immediately across all users.", "The authority URL defines the Microsoft identity tenant endpoint used for sign-in.": "The authority URL defines the Microsoft identity tenant endpoint used for sign-in.", "This will expire all remember-me tokens immediately and force users to sign in again.": "This will expire all remember-me tokens immediately and force users to sign in again.", - "Global settings are stored in the database. config/settings.php is only a runtime cache for selected app settings.": "Global settings are stored in the database. config/settings.php is only a runtime cache for selected app settings.", + "Global settings are stored in the database. storage/runtime/settings.php is only a runtime cache for selected app settings.": "Global settings are stored in the database. storage/runtime/settings.php is only a runtime cache for selected app settings.", "Create your account": "Create your account", "First name": "First name", "Name": "Name", @@ -376,11 +376,16 @@ "Search...": "Search...", "To start searching, type in the search field.": "To start searching, type in the search field.", "Tip: Use {shortcut} to focus search quickly.": "Tip: Use {shortcut} to focus search quickly.", + "Search users, tenants, pages...": "Search users, tenants, pages...", + "Users, tenants, departments, roles and more": "Users, tenants, departments, roles and more", "Searching...": "Searching...", "Search failed. Please try again.": "Search failed. Please try again.", "No results found": "No results found", "View all results": "View all results", "to close": "to close", + "navigate": "navigate", + "open": "open", + "close": "close", "Created from": "Created from", "Created to": "Created to", "Files": "Files", diff --git a/lib/Http/AccessControl.php b/lib/Http/AccessControl.php index fe6d7b4..a73cd03 100644 --- a/lib/Http/AccessControl.php +++ b/lib/Http/AccessControl.php @@ -22,9 +22,18 @@ class AccessControl private array $configuredPublicPaths; private IntendedUrlService $intendedUrlService; - public function __construct(?array $publicPaths = null, ?IntendedUrlService $intendedUrlService = null) + public function __construct(array $publicPaths = [], ?IntendedUrlService $intendedUrlService = null) { - $this->configuredPublicPaths = $publicPaths ?? (defined('APP_PUBLIC_PATHS') ? APP_PUBLIC_PATHS : []); + $normalizedPaths = []; + foreach ($publicPaths as $path) { + $rawPath = trim((string) $path); + if ($rawPath === '') { + continue; + } + $normalizedPaths[] = $rawPath === '/' ? '/' : trim($rawPath, '/'); + } + + $this->configuredPublicPaths = array_values(array_unique($normalizedPaths)); $this->intendedUrlService = $intendedUrlService ?? new IntendedUrlService(); } diff --git a/lib/Http/RouteCatalog.php b/lib/Http/RouteCatalog.php new file mode 100644 index 0000000..ee2f5d0 --- /dev/null +++ b/lib/Http/RouteCatalog.php @@ -0,0 +1,100 @@ + */ + private array $coreRoutes; + + /** @var list */ + private array $corePublicPaths; + + /** + * @param list $coreRoutes + * @param list $corePublicPaths + */ + private function __construct(array $coreRoutes, array $corePublicPaths) + { + $this->coreRoutes = $coreRoutes; + $this->corePublicPaths = $corePublicPaths; + } + + public static function fromConfigFile(string $routesFile): self + { + if (!is_file($routesFile)) { + throw new RuntimeException("Core route config not found: {$routesFile}"); + } + + $loaded = include $routesFile; + if (!is_array($loaded)) { + throw new RuntimeException("Core route config '{$routesFile}' must return an array."); + } + + return self::fromArray($loaded, $routesFile); + } + + /** + * @param array $routes + */ + public static function fromArray(array $routes, string $source = 'config/routes.php'): self + { + $normalized = []; + $publicPaths = []; + $seenPaths = []; + + foreach (array_values($routes) as $index => $route) { + if (!is_array($route)) { + throw new RuntimeException("Invalid route definition at {$source}[{$index}]: expected array."); + } + + $path = trim((string) ($route['path'] ?? '')); + $target = trim((string) ($route['target'] ?? '')); + if ($path === '' || $target === '') { + throw new RuntimeException("Invalid route definition at {$source}[{$index}]: non-empty path and target are required."); + } + + if (isset($seenPaths[$path])) { + throw new RuntimeException("Core route path conflict: '{$path}' is defined multiple times in {$source}."); + } + $seenPaths[$path] = true; + + $isPublic = (bool) ($route['public'] ?? false); + $normalized[] = [ + 'path' => $path, + 'target' => $target, + 'public' => $isPublic, + ]; + + if ($isPublic) { + $publicPaths[] = $path; + } + } + + $publicPaths = array_values(array_unique($publicPaths)); + sort($publicPaths); + + return new self($normalized, $publicPaths); + } + + /** + * @return list + */ + public function coreRoutes(): array + { + return $this->coreRoutes; + } + + /** + * @return list + */ + public function corePublicPaths(): array + { + return $this->corePublicPaths; + } +} diff --git a/lib/Http/RouteRegistrar.php b/lib/Http/RouteRegistrar.php new file mode 100644 index 0000000..a6766d8 --- /dev/null +++ b/lib/Http/RouteRegistrar.php @@ -0,0 +1,56 @@ +coreRoutes() as $route) { + $path = trim((string) ($route['path'] ?? '')); + $target = trim((string) ($route['target'] ?? '')); + if ($path === '' || $target === '') { + continue; + } + + $coreRoutePaths[$path] = $target; + Router::addRoute($path, $target); + } + + $modulePaths = []; + foreach ($this->moduleRegistry->getRoutes() as $route) { + $path = trim((string) ($route['path'] ?? '')); + $target = trim((string) ($route['target'] ?? '')); + $moduleId = trim((string) ($route['module_id'] ?? '')); + if ($path === '' || $target === '') { + continue; + } + + if (isset($coreRoutePaths[$path])) { + throw new RuntimeException( + "Module route path conflict: '{$path}' from module '{$moduleId}' collides with core route target '{$coreRoutePaths[$path]}'." + ); + } + if (isset($modulePaths[$path])) { + throw new RuntimeException( + "Module route path conflict: '{$path}' from module '{$moduleId}' collides with module '{$modulePaths[$path]}'." + ); + } + + $modulePaths[$path] = $moduleId; + Router::addRoute($path, $target); + } + } +} diff --git a/lib/Service/Settings/SettingCacheService.php b/lib/Service/Settings/SettingCacheService.php index f6164ed..30f8f92 100644 --- a/lib/Service/Settings/SettingCacheService.php +++ b/lib/Service/Settings/SettingCacheService.php @@ -4,12 +4,23 @@ namespace MintyPHP\Service\Settings; class SettingCacheService { + private const HOT_PATH_KEYS = [ + SettingKeys::APP_TITLE_KEY, + SettingKeys::APP_LOCALE_KEY, + SettingKeys::APP_THEME_KEY, + SettingKeys::APP_THEME_USER_KEY, + SettingKeys::APP_REGISTRATION_KEY, + SettingKeys::APP_PRIMARY_COLOR_KEY, + ]; + private ?array $settings = null; private ?string $cacheFilePath; + private ?SettingsMetadataGateway $settingsMetadataGateway; - public function __construct(?string $cacheFilePath = null) + public function __construct(?string $cacheFilePath = null, ?SettingsMetadataGateway $settingsMetadataGateway = null) { $this->cacheFilePath = $cacheFilePath; + $this->settingsMetadataGateway = $settingsMetadataGateway; } public function get(string $key): ?string @@ -31,7 +42,7 @@ class SettingCacheService $file = $this->filePath(); if (!is_file($file)) { - $this->settings = []; + $this->settings = $this->hydrateColdStartCache(); return $this->settings; } @@ -90,7 +101,35 @@ class SettingCacheService if (is_string($this->cacheFilePath) && $this->cacheFilePath !== '') { return $this->cacheFilePath; } - return dirname(__DIR__, 3) . '/config/settings.php'; + + $storagePath = defined('APP_STORAGE_PATH') + ? (string) APP_STORAGE_PATH + : dirname(__DIR__, 3) . '/storage'; + + return rtrim($storagePath, '/') . '/runtime/settings.php'; + } + + private function hydrateColdStartCache(): array + { + if (!$this->settingsMetadataGateway instanceof SettingsMetadataGateway) { + return []; + } + + $hydrated = []; + foreach (self::HOT_PATH_KEYS as $key) { + $value = $this->settingsMetadataGateway->getValue($key); + if ($value === null) { + continue; + } + $hydrated[$key] = (string) $value; + } + + if ($this->write($hydrated)) { + return $this->settings ?? $hydrated; + } + + $this->settings = $hydrated; + return $hydrated; } private function exportValue(mixed $value, int $depth = 0): string diff --git a/lib/Service/Settings/SettingServicesFactory.php b/lib/Service/Settings/SettingServicesFactory.php index 020a2d9..2f80e59 100644 --- a/lib/Service/Settings/SettingServicesFactory.php +++ b/lib/Service/Settings/SettingServicesFactory.php @@ -102,7 +102,10 @@ class SettingServicesFactory public function createSettingCacheService(): SettingCacheService { - return $this->settingCacheService ??= new SettingCacheService(); + return $this->settingCacheService ??= new SettingCacheService( + null, + $this->createSettingsMetadataGateway() + ); } public function createThemeConfigGateway(): ThemeConfigGateway diff --git a/lib/Support/helpers/app.php b/lib/Support/helpers/app.php index 8910659..fe9cb44 100644 --- a/lib/Support/helpers/app.php +++ b/lib/Support/helpers/app.php @@ -186,7 +186,7 @@ function appLogoUrlAbsolute(int $size = 128): string } /** - * Read one cached app setting from config/settings.php. + * Read one cached app setting from storage/runtime/settings.php. */ function appSetting(string $key): ?string { diff --git a/pages/admin/settings/index(default).phtml b/pages/admin/settings/index(default).phtml index d3ae71b..fc39b6f 100644 --- a/pages/admin/settings/index(default).phtml +++ b/pages/admin/settings/index(default).phtml @@ -835,7 +835,7 @@ $disabledAttr = $isReadOnly ? 'disabled' : '';
- +
diff --git a/tests/App/Module/RouterConfigCollisionTest.php b/tests/App/Module/RouterConfigCollisionTest.php index 5dd6e20..03f8e0f 100644 --- a/tests/App/Module/RouterConfigCollisionTest.php +++ b/tests/App/Module/RouterConfigCollisionTest.php @@ -4,6 +4,8 @@ namespace MintyPHP\Tests\App\Module; use MintyPHP\App\AppContainer; use MintyPHP\App\Module\ModuleRegistry; +use MintyPHP\Http\RouteCatalog; +use MintyPHP\Http\RouteRegistrar; use MintyPHP\Tests\Support\AppContainerIsolationTrait; use PHPUnit\Framework\TestCase; @@ -27,6 +29,12 @@ final class RouterConfigCollisionTest extends TestCase ], ], true) . ';' ); + file_put_contents( + $fixturesDir . '/core-routes.php', + ' 'login', 'target' => 'auth/login'], + ], true) . ';' + ); try { $registry = ModuleRegistry::boot($fixturesDir, ['mod-a']); @@ -35,18 +43,14 @@ final class RouterConfigCollisionTest extends TestCase $container->set(ModuleRegistry::class, static fn (): ModuleRegistry => $registry); $this->pushAppContainer($container); - if (!defined('APP_ROUTE_DEFINITIONS')) { - define('APP_ROUTE_DEFINITIONS', [ - ['path' => 'login', 'target' => 'auth/login'], - ]); - } - $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Module route path conflict'); - require dirname(__DIR__, 3) . '/config/router.php'; + $catalog = RouteCatalog::fromConfigFile($fixturesDir . '/core-routes.php'); + (new RouteRegistrar($registry))->register($catalog); } finally { $this->restoreAppContainer(); + @unlink($fixturesDir . '/core-routes.php'); @unlink($fixturesDir . '/mod-a/module.php'); @rmdir($fixturesDir . '/mod-a'); @rmdir($fixturesDir); diff --git a/tests/Architecture/ConfigContractsTest.php b/tests/Architecture/ConfigContractsTest.php new file mode 100644 index 0000000..f712f82 --- /dev/null +++ b/tests/Architecture/ConfigContractsTest.php @@ -0,0 +1,107 @@ +assertFileExists($this->projectRootPath() . '/' . $file, 'Missing required config file: ' . $file); + } + + $forbidden = [ + 'config/router.php', + 'config/settings.php', + ]; + foreach ($forbidden as $file) { + $this->assertFileDoesNotExist($this->projectRootPath() . '/' . $file, 'Forbidden runtime config file exists: ' . $file); + } + } + + public function testConfigExampleDoesNotDefineLegacyRouteConstants(): void + { + $content = $this->readProjectFile('config/config.php.example'); + + $this->assertStringNotContainsString('APP_ROUTE_DEFINITIONS', $content); + $this->assertStringNotContainsString('APP_PUBLIC_PATHS', $content); + } + + public function testRuntimePathsDoNotReferenceLegacyRouteConstants(): void + { + $runtimeFiles = $this->runtimeSourceFiles(); + $patterns = [ + '/\bAPP_ROUTE_DEFINITIONS\b/' => 'APP_ROUTE_DEFINITIONS', + '/\bAPP_PUBLIC_PATHS\b/' => 'APP_PUBLIC_PATHS', + ]; + + $violations = []; + foreach ($runtimeFiles as $relativePath) { + $content = $this->readProjectFile($relativePath); + foreach ($patterns as $regex => $label) { + if (preg_match($regex, $content)) { + $violations[] = $relativePath . ': ' . $label; + } + } + } + + $violations = array_values(array_unique($violations)); + sort($violations); + + $this->assertSame( + [], + $violations, + "Legacy route constants referenced in runtime paths:\n" . implode("\n", $violations) + ); + } + + /** + * @return list + */ + private function runtimeSourceFiles(): array + { + $root = $this->projectRootPath(); + $scanTargets = ['lib', 'pages', 'templates', 'web']; + $extensions = ['php', 'phtml', 'js']; + + $files = []; + foreach ($scanTargets as $target) { + $fullPath = $root . '/' . $target; + if (!is_dir($fullPath)) { + continue; + } + + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($fullPath, \FilesystemIterator::SKIP_DOTS) + ); + + foreach ($iterator as $file) { + if (!$file->isFile()) { + continue; + } + + $extension = strtolower((string) $file->getExtension()); + if (!in_array($extension, $extensions, true)) { + continue; + } + + $files[] = str_replace($root . '/', '', $file->getPathname()); + } + } + + $files = array_values(array_unique($files)); + sort($files); + return $files; + } +} diff --git a/tests/Http/RouteCatalogTest.php b/tests/Http/RouteCatalogTest.php new file mode 100644 index 0000000..064f9a3 --- /dev/null +++ b/tests/Http/RouteCatalogTest.php @@ -0,0 +1,90 @@ + */ + private array $tempFiles = []; + + /** @var list */ + private array $tempDirs = []; + + protected function tearDown(): void + { + foreach ($this->tempFiles as $file) { + @unlink($file); + } + foreach ($this->tempDirs as $dir) { + @rmdir($dir); + } + } + + public function testLoadsCoreRoutesAndPublicPathsFromConfigFile(): void + { + $routesFile = $this->createRoutesFile([ + ['path' => 'login', 'target' => 'auth/login', 'public' => true], + ['path' => 'profile', 'target' => 'account/profile', 'public' => false], + ]); + + $catalog = RouteCatalog::fromConfigFile($routesFile); + + self::assertSame( + [ + ['path' => 'login', 'target' => 'auth/login', 'public' => true], + ['path' => 'profile', 'target' => 'account/profile', 'public' => false], + ], + $catalog->coreRoutes() + ); + self::assertSame(['login'], $catalog->corePublicPaths()); + } + + public function testThrowsWhenRouteConfigDoesNotReturnArray(): void + { + $routesFile = $this->createRawConfigFile("expectException(RuntimeException::class); + $this->expectExceptionMessage('must return an array'); + + RouteCatalog::fromConfigFile($routesFile); + } + + public function testThrowsForInvalidRouteShape(): void + { + $routesFile = $this->createRoutesFile([ + ['path' => 'login'], + ]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Invalid route definition'); + + RouteCatalog::fromConfigFile($routesFile); + } + + /** + * @param list> $routes + */ + private function createRoutesFile(array $routes): string + { + return $this->createRawConfigFile( + 'tempFiles[] = $file; + $this->tempDirs[] = $dir; + return $file; + } +} diff --git a/tests/Service/Settings/SettingCacheServiceTest.php b/tests/Service/Settings/SettingCacheServiceTest.php index d99d8aa..18eb2ac 100644 --- a/tests/Service/Settings/SettingCacheServiceTest.php +++ b/tests/Service/Settings/SettingCacheServiceTest.php @@ -3,6 +3,8 @@ namespace MintyPHP\Tests\Service\Settings; use MintyPHP\Service\Settings\SettingCacheService; +use MintyPHP\Service\Settings\SettingKeys; +use MintyPHP\Service\Settings\SettingsMetadataGateway; use PHPUnit\Framework\TestCase; class SettingCacheServiceTest extends TestCase @@ -31,6 +33,42 @@ class SettingCacheServiceTest extends TestCase $this->assertNull($service->get('app_locale')); } + public function testDefaultFilePathUsesStorageRuntimeSettingsFile(): void + { + $service = new SettingCacheService(); + + $this->assertStringEndsWith('/storage/runtime/settings.php', $service->filePath()); + } + + public function testColdStartHydratesHotPathKeysFromDatabaseAndWritesCacheFile(): void + { + $file = $this->tempFilePath(); + + $metadataGateway = $this->createMock(SettingsMetadataGateway::class); + $metadataGateway->expects($this->exactly(6)) + ->method('getValue') + ->willReturnCallback(static function (string $key): ?string { + return match ($key) { + SettingKeys::APP_TITLE_KEY => 'Demo App', + SettingKeys::APP_LOCALE_KEY => 'de', + SettingKeys::APP_THEME_KEY => 'dark', + SettingKeys::APP_THEME_USER_KEY => '1', + SettingKeys::APP_REGISTRATION_KEY => '0', + SettingKeys::APP_PRIMARY_COLOR_KEY => '#112233', + default => null, + }; + }); + + $service = new SettingCacheService($file, $metadataGateway); + $this->assertSame('Demo App', $service->get('app_title')); + $this->assertFileExists($file); + + /** @var array $cache */ + $cache = include $file; + $this->assertSame('de', $cache[SettingKeys::APP_LOCALE_KEY] ?? null); + $this->assertSame('#112233', $cache[SettingKeys::APP_PRIMARY_COLOR_KEY] ?? null); + } + private function tempFilePath(): string { $dir = sys_get_temp_dir() . '/mintyphp_settings_cache_test_' . bin2hex(random_bytes(6)); diff --git a/web/index.php b/web/index.php index 636169a..d1533c5 100644 --- a/web/index.php +++ b/web/index.php @@ -11,6 +11,8 @@ use MintyPHP\Http\IntendedUrlService; use MintyPHP\Http\LocaleResolver; use MintyPHP\Http\RequestContext; use MintyPHP\Http\Request; +use MintyPHP\Http\RouteCatalog; +use MintyPHP\Http\RouteRegistrar; use MintyPHP\I18n; use MintyPHP\Router; use MintyPHP\App\Module\ModuleRegistry; @@ -55,7 +57,9 @@ if (count($activeModules) > 0 || is_dir($runtimePageRoot) || is_link($runtimePag // ── 3. Routes ─────────────────────────────────────────────────────── -require 'config/router.php'; +$routeCatalog = RouteCatalog::fromConfigFile(__DIR__ . '/../config/routes.php'); +(new RouteRegistrar($moduleRegistry))->register($routeCatalog); +$corePublicPaths = $routeCatalog->corePublicPaths(); // ── 4. Request context ────────────────────────────────────────────── @@ -246,7 +250,7 @@ if (!$isApiRequest) { // ── 8. Access control guard ───────────────────────────────────────── $allPublicPaths = array_values(array_unique(array_merge( - defined('APP_PUBLIC_PATHS') ? APP_PUBLIC_PATHS : [], + $corePublicPaths, $moduleRegistry->getPublicPaths() ))); $accessControl = new AccessControl($allPublicPaths, app(IntendedUrlService::class));