1
0

refactor(config): remove runtime config files and centralize route/bootstrap

This commit is contained in:
2026-04-01 20:27:42 +02:00
parent dba589b495
commit 5699bc6c5b
20 changed files with 487 additions and 118 deletions

View File

@@ -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",

View File

@@ -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/<id>/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)

View File

@@ -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: '/'

View File

@@ -1,50 +0,0 @@
<?php
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Router;
$routesFile = __DIR__ . '/routes.php';
$routeDefinitions = defined('APP_ROUTE_DEFINITIONS') ? APP_ROUTE_DEFINITIONS : [];
if (!is_array($routeDefinitions) || !$routeDefinitions) {
$routeDefinitions = is_file($routesFile) ? include $routesFile : [];
}
$coreRoutePaths = [];
if (is_array($routeDefinitions)) {
foreach ($routeDefinitions as $route) {
$path = trim((string) ($route['path'] ?? ''));
$target = trim((string) ($route['target'] ?? ''));
if ($path === '' || $target === '') {
continue;
}
$coreRoutePaths[$path] = $target;
Router::addRoute($path, $target);
}
}
// ── Module routes ────────────────────────────────────────────────────
// Module routes are merged after core routes. web/index.php includes this file
// only after container bootstrap, so ModuleRegistry is available here.
if (app(ModuleRegistry::class) instanceof ModuleRegistry) {
$moduleRegistry = app(ModuleRegistry::class);
$modulePaths = [];
foreach ($moduleRegistry->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);
}
}
}

View File

@@ -1,17 +0,0 @@
<?php
return [
'app_title' => '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',
];

View File

@@ -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

View File

@@ -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",

View File

@@ -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",

View File

@@ -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();
}

100
lib/Http/RouteCatalog.php Normal file
View File

@@ -0,0 +1,100 @@
<?php
namespace MintyPHP\Http;
use RuntimeException;
/**
* Loads and validates core route declarations from config/routes.php.
*/
final class RouteCatalog
{
/** @var list<array{path: string, target: string, public: bool}> */
private array $coreRoutes;
/** @var list<string> */
private array $corePublicPaths;
/**
* @param list<array{path: string, target: string, public: bool}> $coreRoutes
* @param list<string> $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<mixed> $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<array{path: string, target: string, public: bool}>
*/
public function coreRoutes(): array
{
return $this->coreRoutes;
}
/**
* @return list<string>
*/
public function corePublicPaths(): array
{
return $this->corePublicPaths;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace MintyPHP\Http;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Router;
use RuntimeException;
/**
* Registers core + module routes into the runtime router.
*/
final class RouteRegistrar
{
public function __construct(private readonly ModuleRegistry $moduleRegistry)
{
}
public function register(RouteCatalog $catalog): void
{
$coreRoutePaths = [];
foreach ($catalog->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);
}
}
}

View File

@@ -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

View File

@@ -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

View File

@@ -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
{

View File

@@ -835,7 +835,7 @@ $disabledAttr = $isReadOnly ? 'disabled' : '';
<?php endif; ?>
<hr>
<blockquote data-variant="info">
<?php e(t('Global settings are stored in the database. config/settings.php is only a runtime cache for selected app settings.')); ?>
<?php e(t('Global settings are stored in the database. storage/runtime/settings.php is only a runtime cache for selected app settings.')); ?>
</blockquote>
</div>
</aside>

View File

@@ -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',
'<?php return ' . var_export([
['path' => '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);

View File

@@ -0,0 +1,107 @@
<?php
namespace MintyPHP\Tests\Architecture;
use PHPUnit\Framework\TestCase;
final class ConfigContractsTest extends TestCase
{
use ProjectFileAssertionSupport;
public function testConfigDirectoryContainsOnlyDeclarativeConfigFiles(): void
{
$required = [
'config/assets.php',
'config/routes.php',
'config/modules.php',
'config/themes.php',
'config/config.php.example',
];
foreach ($required as $file) {
$this->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<string>
*/
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;
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace MintyPHP\Tests\Http;
use MintyPHP\Http\RouteCatalog;
use PHPUnit\Framework\TestCase;
use RuntimeException;
final class RouteCatalogTest extends TestCase
{
/** @var list<string> */
private array $tempFiles = [];
/** @var list<string> */
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("<?php return 'invalid';\n");
$this->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<array<string, mixed>> $routes
*/
private function createRoutesFile(array $routes): string
{
return $this->createRawConfigFile(
'<?php return ' . var_export($routes, true) . ";\n"
);
}
private function createRawConfigFile(string $contents): string
{
$dir = sys_get_temp_dir() . '/route-catalog-test-' . uniqid('', true);
mkdir($dir, 0777, true);
$file = $dir . '/routes.php';
file_put_contents($file, $contents);
$this->tempFiles[] = $file;
$this->tempDirs[] = $dir;
return $file;
}
}

View File

@@ -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<string, string> $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));

View File

@@ -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));