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

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

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

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

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

View File

@@ -16,7 +16,6 @@ class OperationsAuthorizationPolicyTest extends TestCase
{
$policy = new OperationsAuthorizationPolicy($this->createMock(PermissionService::class));
$this->assertTrue($policy->supports(OperationsAuthorizationPolicy::ABILITY_ADDRESS_BOOK_VIEW));
$this->assertTrue($policy->supports(OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_VIEW));
$this->assertTrue($policy->supports(OperationsAuthorizationPolicy::ABILITY_API_TENANTS_DELETE));
$this->assertTrue($policy->supports(OperationsAuthorizationPolicy::ABILITY_API_TOKENS_SELF_MANAGE));
@@ -40,7 +39,7 @@ class OperationsAuthorizationPolicyTest extends TestCase
$permissionService->expects($this->never())->method('userHas');
$policy = new OperationsAuthorizationPolicy($permissionService);
$decision = $policy->authorize(OperationsAuthorizationPolicy::ABILITY_ADDRESS_BOOK_VIEW, [
$decision = $policy->authorize(OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_VIEW, [
'actor_user_id' => 0,
]);
@@ -83,31 +82,7 @@ class OperationsAuthorizationPolicyTest extends TestCase
// --- authorize: allowIfHas (simple permission check) ---
public function testAddressBookViewAllowedWithPermission(): void
{
$permissionService = $this->permissionGatewayAllowing([
5 => [PermissionService::ADDRESS_BOOK_VIEW],
]);
$policy = new OperationsAuthorizationPolicy($permissionService);
$decision = $policy->authorize(OperationsAuthorizationPolicy::ABILITY_ADDRESS_BOOK_VIEW, [
'actor_user_id' => 5,
]);
$this->assertTrue($decision->isAllowed());
}
public function testAddressBookViewDeniedWithoutPermission(): void
{
$permissionService = $this->permissionGatewayAllowing([5 => []]);
$policy = new OperationsAuthorizationPolicy($permissionService);
$decision = $policy->authorize(OperationsAuthorizationPolicy::ABILITY_ADDRESS_BOOK_VIEW, [
'actor_user_id' => 5,
]);
$this->assertForbiddenDecision($decision);
}
// Address book ability tests moved to AddressBookAuthorizationPolicyTest (module-owned).
public function testJobsViewAllowedWithPermission(): void
{

View File

@@ -2,9 +2,11 @@
namespace MintyPHP\Tests\Service\Auth;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\SessionProvider;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Http\SessionStore;
use MintyPHP\Service\Auth\AuthSessionTenantContextService;
use MintyPHP\Service\Bookmark\BookmarkService;
use MintyPHP\Service\User\UserTenantContextService;
use PHPUnit\Framework\TestCase;
@@ -13,6 +15,8 @@ class AuthSessionTenantContextServiceTest extends TestCase
protected function setUp(): void
{
$_SESSION = [];
DummyAuthSessionProvider::$populateCalls = 0;
DummyAuthSessionProvider::$clearCalls = 0;
}
public function testHydrateMarksNoActiveTenantWhenUserHasNoTenants(): void
@@ -21,25 +25,16 @@ class AuthSessionTenantContextServiceTest extends TestCase
$userTenantContextService = $this->createMock(UserTenantContextService::class);
$userTenantContextService->method('getAvailableTenants')->willReturn([]);
$userTenantContextService->method('getAvailableDepartmentsByTenant')->willReturn([]);
$userTenantContextService->expects($this->never())->method('getCurrentTenant');
$bookmarkService = $this->createMock(BookmarkService::class);
$bookmarkService->method('listGroupedForUser')->willReturn(['groups' => [], 'ungrouped' => []]);
$service = new AuthSessionTenantContextService(
$userTenantContextService,
$bookmarkService,
new SessionStore()
);
$service = $this->createService($userTenantContextService);
$service->hydrateForUser(5);
$this->assertSame([], $_SESSION['available_tenants']);
$this->assertSame([], $_SESSION['available_departments_by_tenant']);
$this->assertSame(['groups' => [], 'ungrouped' => []], $_SESSION['user_bookmarks']);
$this->assertTrue((bool) $_SESSION['no_active_tenant']);
$this->assertArrayNotHasKey('current_tenant', $_SESSION);
$this->assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
}
public function testHydrateUsesFirstAvailableTenantAsFallback(): void
@@ -48,30 +43,18 @@ class AuthSessionTenantContextServiceTest extends TestCase
['id' => 7, 'uuid' => 'tenant-7'],
['id' => 8, 'uuid' => 'tenant-8'],
];
$availableDepartments = ['7' => [['id' => 11]]];
$bookmarks = ['groups' => [['id' => 1, 'name' => 'Dev', 'bookmarks' => []]], 'ungrouped' => []];
$userTenantContextService = $this->createMock(UserTenantContextService::class);
$userTenantContextService->method('getAvailableTenants')->willReturn($availableTenants);
$userTenantContextService->method('getAvailableDepartmentsByTenant')->willReturn($availableDepartments);
$userTenantContextService->method('getCurrentTenant')->willReturn(null);
$bookmarkService = $this->createMock(BookmarkService::class);
$bookmarkService->method('listGroupedForUser')->willReturn($bookmarks);
$service = new AuthSessionTenantContextService(
$userTenantContextService,
$bookmarkService,
new SessionStore()
);
$service = $this->createService($userTenantContextService);
$service->hydrateForUser(5);
$this->assertSame($availableTenants, $_SESSION['available_tenants']);
$this->assertSame($availableDepartments, $_SESSION['available_departments_by_tenant']);
$this->assertSame($bookmarks, $_SESSION['user_bookmarks']);
$this->assertFalse((bool) $_SESSION['no_active_tenant']);
$this->assertSame(7, (int) ($_SESSION['current_tenant']['id'] ?? 0));
$this->assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
}
public function testHydratePreservesThemeAndPolicyFieldsInSession(): void
@@ -87,17 +70,9 @@ class AuthSessionTenantContextServiceTest extends TestCase
$userTenantContextService = $this->createMock(UserTenantContextService::class);
$userTenantContextService->method('getAvailableTenants')->willReturn($availableTenants);
$userTenantContextService->method('getAvailableDepartmentsByTenant')->willReturn([]);
$userTenantContextService->method('getCurrentTenant')->willReturn($availableTenants[0]);
$bookmarkService = $this->createMock(BookmarkService::class);
$bookmarkService->method('listGroupedForUser')->willReturn(['groups' => [], 'ungrouped' => []]);
$service = new AuthSessionTenantContextService(
$userTenantContextService,
$bookmarkService,
new SessionStore()
);
$service = $this->createService($userTenantContextService);
$service->hydrateForUser(10);
@@ -105,4 +80,73 @@ class AuthSessionTenantContextServiceTest extends TestCase
$this->assertSame('dark', $tenant['default_theme'] ?? null);
$this->assertSame('0', $tenant['allow_user_theme'] ?? null);
}
public function testHydrateAndClearInvokeConfiguredModuleSessionProviders(): void
{
$fixturesDir = sys_get_temp_dir() . '/auth-session-provider-test-' . uniqid();
mkdir($fixturesDir . '/mod-session', 0777, true);
file_put_contents(
$fixturesDir . '/mod-session/module.php',
'<?php return ' . var_export([
'id' => 'mod-session',
'session_providers' => [DummyAuthSessionProvider::class],
], true) . ';'
);
try {
$registry = ModuleRegistry::boot($fixturesDir, ['mod-session']);
$userTenantContextService = $this->createMock(UserTenantContextService::class);
$userTenantContextService->method('getAvailableTenants')->willReturn([['id' => 7, 'uuid' => 'tenant-7']]);
$userTenantContextService->method('getCurrentTenant')->willReturn(['id' => 7, 'uuid' => 'tenant-7']);
$service = $this->createService($userTenantContextService, $registry);
$_SESSION['user'] = ['id' => 42];
$service->hydrateForUser(42);
$this->assertSame(1, DummyAuthSessionProvider::$populateCalls);
$this->assertSame(42, (int) ($_SESSION['dummy_provider_user_id'] ?? 0));
$service->clearModuleSessionData();
$this->assertSame(1, DummyAuthSessionProvider::$clearCalls);
$this->assertArrayNotHasKey('dummy_provider_user_id', $_SESSION);
} finally {
@unlink($fixturesDir . '/mod-session/module.php');
@rmdir($fixturesDir . '/mod-session');
@rmdir($fixturesDir);
}
}
private function createService(
UserTenantContextService $userTenantContextService,
?ModuleRegistry $registry = null
): AuthSessionTenantContextService {
$registry ??= ModuleRegistry::boot(sys_get_temp_dir() . '/module-registry-empty-' . uniqid(), []);
$container = new AppContainer();
$container->set(ModuleRegistry::class, static fn (): ModuleRegistry => $registry);
return new AuthSessionTenantContextService(
$userTenantContextService,
new SessionStore(),
$container
);
}
}
final class DummyAuthSessionProvider implements SessionProvider
{
public static int $populateCalls = 0;
public static int $clearCalls = 0;
public function populate(array $user, AppContainer $container): void
{
self::$populateCalls++;
$_SESSION['dummy_provider_user_id'] = (int) ($user['id'] ?? 0);
}
public function clear(): void
{
self::$clearCalls++;
unset($_SESSION['dummy_provider_user_id']);
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace MintyPHP\Tests\Service\Scheduler;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Service\Scheduler\Handler\ScheduledJobHandlerInterface;
use MintyPHP\Service\Scheduler\ScheduledJobRegistry;
use MintyPHP\Service\User\UserLifecycleService;
use PHPUnit\Framework\TestCase;
final class ScheduledJobRegistryTest extends TestCase
{
private string $fixturesDir = '';
protected function setUp(): void
{
$this->fixturesDir = sys_get_temp_dir() . '/scheduler-module-registry-' . uniqid();
mkdir($this->fixturesDir, 0777, true);
}
protected function tearDown(): void
{
$this->removeDir($this->fixturesDir);
}
public function testModuleJobAppearsInDefinitionsAndIsExecutable(): void
{
$moduleRegistry = $this->createRegistryWithModuleJob();
$container = new AppContainer();
$container->set(ModuleRegistry::class, static fn (): ModuleRegistry => $moduleRegistry);
$container->set(
DummyModuleScheduledJobHandler::class,
static fn (): DummyModuleScheduledJobHandler => new DummyModuleScheduledJobHandler()
);
$registry = new ScheduledJobRegistry(
$this->createMock(UserLifecycleService::class),
$this->createMock(SystemAuditService::class),
$container
);
$definitions = $registry->definitions();
self::assertArrayHasKey('addressbook.sync', $definitions);
self::assertSame('Address book sync', $definitions['addressbook.sync']['label'] ?? null);
$execution = $registry->execute('addressbook.sync', 123);
self::assertSame('success', $execution['status']);
self::assertSame(['actor' => 123], $execution['result']);
}
private function createRegistryWithModuleJob(): ModuleRegistry
{
mkdir($this->fixturesDir . '/mod-job', 0777, true);
file_put_contents(
$this->fixturesDir . '/mod-job/module.php',
'<?php return ' . var_export([
'id' => 'mod-job',
'scheduler_jobs' => [[
'job_key' => 'addressbook.sync',
'handler' => DummyModuleScheduledJobHandler::class,
'label' => 'Address book sync',
'description' => 'Sync job',
'default_enabled' => true,
'default_timezone' => 'UTC',
'default_schedule_type' => 'daily',
'default_schedule_interval' => 1,
'default_schedule_time' => '03:00',
'default_schedule_weekdays_csv' => null,
'default_catchup_once' => true,
'allowed_schedule_types' => ['daily', 'weekly'],
]],
], true) . ';'
);
return ModuleRegistry::boot($this->fixturesDir, ['mod-job']);
}
private function removeDir(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$items = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item) {
if ($item->isDir()) {
rmdir($item->getPathname());
} else {
unlink($item->getPathname());
}
}
rmdir($dir);
}
}
final class DummyModuleScheduledJobHandler implements ScheduledJobHandlerInterface
{
public function definition(): array
{
return [
'label' => 'dummy',
'description' => 'dummy',
'default_enabled' => 1,
'default_timezone' => 'UTC',
'default_schedule_type' => 'daily',
'default_schedule_interval' => 1,
'default_schedule_time' => '00:00',
'default_schedule_weekdays_csv' => null,
'default_catchup_once' => 1,
'allowed_schedule_types' => ['daily'],
];
}
public function execute(?int $actorUserId): array
{
return [
'status' => 'success',
'error_code' => null,
'error_message' => null,
'result' => ['actor' => $actorUserId],
];
}
}

View File

@@ -11,6 +11,97 @@ use PHPUnit\Framework\TestCase;
class ScheduledJobServiceTest extends TestCase
{
public function testEnsureSystemJobsCreatesModuleJobDefinition(): void
{
$jobRepository = $this->createMock(ScheduledJobRepository::class);
$runRepository = $this->createMock(ScheduledJobRunRepository::class);
$registry = $this->createMock(ScheduledJobRegistry::class);
$calculator = new ScheduleCalculator();
$registry->expects($this->once())->method('definitions')->willReturn([
'addressbook.sync' => [
'label' => 'Addressbook Sync',
'description' => 'Syncs address book data',
'default_enabled' => 1,
'default_timezone' => 'UTC',
'default_schedule_type' => 'daily',
'default_schedule_interval' => 1,
'default_schedule_time' => '03:00',
'default_schedule_weekdays_csv' => null,
'default_catchup_once' => 1,
'allowed_schedule_types' => ['hourly', 'daily', 'weekly'],
],
]);
$jobRepository->expects($this->once())
->method('findByKey')
->with('addressbook.sync')
->willReturn(null);
$jobRepository->expects($this->once())
->method('create')
->with($this->callback(static function (array $job): bool {
return ($job['job_key'] ?? null) === 'addressbook.sync'
&& ($job['label'] ?? null) === 'Addressbook Sync'
&& ($job['timezone'] ?? null) === 'UTC'
&& ($job['schedule_type'] ?? null) === 'daily';
}))
->willReturn(99);
$jobRepository->expects($this->never())->method('updateJobMeta');
$service = new ScheduledJobService($jobRepository, $runRepository, $registry, $calculator);
$service->ensureSystemJobs();
}
public function testEnsureSystemJobsUpdatesExistingModuleJobMetadata(): void
{
$jobRepository = $this->createMock(ScheduledJobRepository::class);
$runRepository = $this->createMock(ScheduledJobRunRepository::class);
$registry = $this->createMock(ScheduledJobRegistry::class);
$calculator = new ScheduleCalculator();
$registry->expects($this->once())->method('definitions')->willReturn([
'addressbook.sync' => [
'label' => 'Addressbook Sync',
'description' => 'Syncs address book data',
'default_enabled' => 1,
'default_timezone' => 'UTC',
'default_schedule_type' => 'daily',
'default_schedule_interval' => 1,
'default_schedule_time' => '03:00',
'default_schedule_weekdays_csv' => null,
'default_catchup_once' => 1,
'allowed_schedule_types' => ['hourly', 'daily', 'weekly'],
],
]);
$jobRepository->expects($this->once())
->method('findByKey')
->with('addressbook.sync')
->willReturn([
'id' => 12,
'job_key' => 'addressbook.sync',
'label' => 'Old Label',
'description' => 'Old description',
'enabled' => 1,
'timezone' => 'UTC',
'schedule_type' => 'daily',
'schedule_interval' => 1,
'schedule_time' => '03:00',
'schedule_weekdays_csv' => null,
'catchup_once' => 1,
'next_run_at' => '2026-01-01 03:00:00',
]);
$jobRepository->expects($this->once())
->method('updateJobMeta')
->with(12, $this->callback(static function (array $job): bool {
return ($job['label'] ?? null) === 'Addressbook Sync'
&& ($job['description'] ?? null) === 'Syncs address book data';
}))
->willReturn(true);
$jobRepository->expects($this->never())->method('create');
$service = new ScheduledJobService($jobRepository, $runRepository, $registry, $calculator);
$service->ensureSystemJobs();
}
public function testUpdateFromAdminReturnsValidationErrorForWeeklyWithoutWeekdays(): void
{
$jobRepository = $this->createMock(ScheduledJobRepository::class);