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:
40
tests/App/AppContainerTest.php
Normal file
40
tests/App/AppContainerTest.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\App;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use RuntimeException;
|
||||
|
||||
final class AppContainerTest extends TestCase
|
||||
{
|
||||
public function testOverwritingBindingIsAllowedBeforeProtection(): void
|
||||
{
|
||||
$container = new AppContainer();
|
||||
$container->set('service.test', static fn (): string => 'first');
|
||||
$container->set('service.test', static fn (): string => 'second');
|
||||
|
||||
self::assertSame('second', $container->get('service.test'));
|
||||
}
|
||||
|
||||
public function testOverwritingExistingBindingIsBlockedAfterProtection(): void
|
||||
{
|
||||
$container = new AppContainer();
|
||||
$container->set('service.test', static fn (): string => 'first');
|
||||
$container->protectExistingBindings();
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage('Refusing to overwrite existing service binding: service.test');
|
||||
$container->set('service.test', static fn (): string => 'second');
|
||||
}
|
||||
|
||||
public function testAddingNewBindingStillWorksAfterProtection(): void
|
||||
{
|
||||
$container = new AppContainer();
|
||||
$container->set('service.first', static fn (): string => 'first');
|
||||
$container->protectExistingBindings();
|
||||
$container->set('service.second', static fn (): string => 'second');
|
||||
|
||||
self::assertSame('second', $container->get('service.second'));
|
||||
}
|
||||
}
|
||||
@@ -35,10 +35,32 @@ final class ModuleManifestTest extends TestCase
|
||||
'ui_slots' => ['aside.tab_panel' => [['key' => 'people', 'label' => 'People']]],
|
||||
'search_resources' => ['App\\SearchProvider'],
|
||||
'asset_groups' => ['address-book' => ['css/view.css']],
|
||||
'scheduler_jobs' => [],
|
||||
'scheduler_jobs' => [
|
||||
[
|
||||
'job_key' => 'addressbook.sync',
|
||||
'handler' => 'App\\Scheduler\\AddressBookSyncHandler',
|
||||
'label' => 'Address book sync',
|
||||
'description' => 'Syncs address data',
|
||||
'default_enabled' => true,
|
||||
'default_timezone' => 'Europe/Berlin',
|
||||
'default_schedule_type' => 'daily',
|
||||
'default_schedule_interval' => 1,
|
||||
'default_schedule_time' => '02:00',
|
||||
'default_schedule_weekdays_csv' => null,
|
||||
'default_catchup_once' => true,
|
||||
'allowed_schedule_types' => ['daily', 'weekly'],
|
||||
],
|
||||
],
|
||||
'layout_context_providers' => ['App\\LayoutProvider'],
|
||||
'session_providers' => ['App\\SessionProvider'],
|
||||
'permissions' => ['address_book.view'],
|
||||
'permissions' => [
|
||||
[
|
||||
'key' => 'address_book.view',
|
||||
'description' => 'Can view address book',
|
||||
'active' => true,
|
||||
'is_system' => true,
|
||||
],
|
||||
],
|
||||
'migrations_path' => 'db/updates',
|
||||
];
|
||||
|
||||
@@ -49,7 +71,13 @@ final class ModuleManifestTest extends TestCase
|
||||
self::assertTrue($manifest->enabledByDefault);
|
||||
self::assertSame(10, $manifest->loadOrder);
|
||||
self::assertCount(1, $manifest->routes);
|
||||
self::assertSame(['address_book.view'], $manifest->permissions);
|
||||
self::assertSame([[
|
||||
'key' => 'address_book.view',
|
||||
'description' => 'Can view address book',
|
||||
'active' => 1,
|
||||
'is_system' => 1,
|
||||
]], $manifest->permissions);
|
||||
self::assertSame('addressbook.sync', $manifest->schedulerJobs[0]['job_key']);
|
||||
self::assertSame('/srv/modules/addressbook/db/updates', $manifest->migrationsPath);
|
||||
self::assertSame(['App\\LayoutProvider'], $manifest->layoutContextProviders);
|
||||
self::assertSame(['App\\SessionProvider'], $manifest->sessionProviders);
|
||||
@@ -69,4 +97,38 @@ final class ModuleManifestTest extends TestCase
|
||||
|
||||
ModuleManifest::fromArray(['id' => ' '], '/tmp/modules/broken');
|
||||
}
|
||||
|
||||
public function testInvalidPermissionContractThrows(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage("must define non-empty 'key' and 'description'");
|
||||
|
||||
ModuleManifest::fromArray([
|
||||
'id' => 'mod-invalid-perm',
|
||||
'permissions' => [['key' => 'mod.permission']],
|
||||
], '/tmp/modules/mod-invalid-perm');
|
||||
}
|
||||
|
||||
public function testInvalidSchedulerJobContractThrows(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage("missing required key 'allowed_schedule_types'");
|
||||
|
||||
ModuleManifest::fromArray([
|
||||
'id' => 'mod-invalid-job',
|
||||
'scheduler_jobs' => [[
|
||||
'job_key' => 'mod.job',
|
||||
'handler' => 'App\\Handler',
|
||||
'label' => 'Label',
|
||||
'description' => 'Desc',
|
||||
'default_enabled' => true,
|
||||
'default_timezone' => 'UTC',
|
||||
'default_schedule_type' => 'daily',
|
||||
'default_schedule_interval' => 1,
|
||||
'default_schedule_time' => '01:00',
|
||||
'default_schedule_weekdays_csv' => null,
|
||||
'default_catchup_once' => true,
|
||||
]],
|
||||
], '/tmp/modules/mod-invalid-job');
|
||||
}
|
||||
}
|
||||
|
||||
181
tests/App/Module/ModulePermissionSynchronizerTest.php
Normal file
181
tests/App/Module/ModulePermissionSynchronizerTest.php
Normal file
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\App\Module;
|
||||
|
||||
use MintyPHP\App\Module\ModulePermissionSynchronizer;
|
||||
use MintyPHP\App\Module\ModuleRegistry;
|
||||
use MintyPHP\Repository\Access\PermissionRepositoryInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ModulePermissionSynchronizerTest extends TestCase
|
||||
{
|
||||
private string $fixturesDir = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->fixturesDir = sys_get_temp_dir() . '/module-permission-sync-' . uniqid();
|
||||
mkdir($this->fixturesDir, 0777, true);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->removeDir($this->fixturesDir);
|
||||
}
|
||||
|
||||
public function testSyncCreatesPermissionAndIsIdempotent(): void
|
||||
{
|
||||
$registry = $this->createRegistryWithPermissions([[
|
||||
'key' => 'address_book.view',
|
||||
'description' => 'Can view address book',
|
||||
'active' => 1,
|
||||
'is_system' => 1,
|
||||
]]);
|
||||
|
||||
$repository = new InMemoryPermissionRepository();
|
||||
$synchronizer = new ModulePermissionSynchronizer($registry, $repository);
|
||||
|
||||
$first = $synchronizer->sync();
|
||||
self::assertSame(1, $first['created']);
|
||||
self::assertSame(0, $first['updated']);
|
||||
self::assertSame(0, $first['unchanged']);
|
||||
|
||||
$second = $synchronizer->sync();
|
||||
self::assertSame(0, $second['created']);
|
||||
self::assertSame(0, $second['updated']);
|
||||
self::assertSame(1, $second['unchanged']);
|
||||
}
|
||||
|
||||
public function testSyncUpdatesExistingPermissionWhenDefinitionChanged(): void
|
||||
{
|
||||
$registry = $this->createRegistryWithPermissions([[
|
||||
'key' => 'address_book.view',
|
||||
'description' => 'Can view address book',
|
||||
'active' => 1,
|
||||
'is_system' => 1,
|
||||
]]);
|
||||
|
||||
$repository = new InMemoryPermissionRepository();
|
||||
$repository->create([
|
||||
'key' => 'address_book.view',
|
||||
'description' => 'Old description',
|
||||
'active' => 0,
|
||||
'is_system' => 0,
|
||||
]);
|
||||
|
||||
$synchronizer = new ModulePermissionSynchronizer($registry, $repository);
|
||||
$result = $synchronizer->sync();
|
||||
|
||||
self::assertSame(0, $result['created']);
|
||||
self::assertSame(1, $result['updated']);
|
||||
self::assertSame(0, $result['unchanged']);
|
||||
|
||||
$permission = $repository->findByKey('address_book.view');
|
||||
self::assertSame('Can view address book', $permission['description'] ?? null);
|
||||
self::assertSame(1, (int) ($permission['active'] ?? 0));
|
||||
self::assertSame(1, (int) ($permission['is_system'] ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{key: string, description: string, active: int, is_system: int}> $permissions
|
||||
*/
|
||||
private function createRegistryWithPermissions(array $permissions): ModuleRegistry
|
||||
{
|
||||
mkdir($this->fixturesDir . '/mod-perm', 0777, true);
|
||||
file_put_contents(
|
||||
$this->fixturesDir . '/mod-perm/module.php',
|
||||
'<?php return ' . var_export([
|
||||
'id' => 'mod-perm',
|
||||
'permissions' => $permissions,
|
||||
], true) . ';'
|
||||
);
|
||||
|
||||
return ModuleRegistry::boot($this->fixturesDir, ['mod-perm']);
|
||||
}
|
||||
|
||||
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 InMemoryPermissionRepository implements PermissionRepositoryInterface
|
||||
{
|
||||
/** @var array<int, array<string, mixed>> */
|
||||
private array $rows = [];
|
||||
private int $nextId = 1;
|
||||
|
||||
public function list(): array
|
||||
{
|
||||
return array_values($this->rows);
|
||||
}
|
||||
|
||||
public function listActive(): array
|
||||
{
|
||||
return array_values(array_filter($this->rows, static fn (array $row): bool => (int) ($row['active'] ?? 0) === 1));
|
||||
}
|
||||
|
||||
public function listPaged(array $options): array
|
||||
{
|
||||
return ['rows' => $this->list(), 'total' => count($this->rows)];
|
||||
}
|
||||
|
||||
public function find(int $id): ?array
|
||||
{
|
||||
return $this->rows[$id] ?? null;
|
||||
}
|
||||
|
||||
public function findByKey(string $key): ?array
|
||||
{
|
||||
foreach ($this->rows as $row) {
|
||||
if ((string) ($row['key'] ?? '') === $key) {
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function create(array $data): ?int
|
||||
{
|
||||
$id = $this->nextId++;
|
||||
$this->rows[$id] = [
|
||||
'id' => $id,
|
||||
'key' => (string) ($data['key'] ?? ''),
|
||||
'description' => (string) ($data['description'] ?? ''),
|
||||
'active' => (int) ($data['active'] ?? 1),
|
||||
'is_system' => (int) ($data['is_system'] ?? 1),
|
||||
];
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function update(int $id, array $data): bool
|
||||
{
|
||||
if (!isset($this->rows[$id])) {
|
||||
return false;
|
||||
}
|
||||
$this->rows[$id]['key'] = (string) ($data['key'] ?? $this->rows[$id]['key']);
|
||||
$this->rows[$id]['description'] = (string) ($data['description'] ?? $this->rows[$id]['description']);
|
||||
$this->rows[$id]['active'] = (int) ($data['active'] ?? $this->rows[$id]['active']);
|
||||
$this->rows[$id]['is_system'] = (int) ($data['is_system'] ?? $this->rows[$id]['is_system']);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function delete(int $id): bool
|
||||
{
|
||||
unset($this->rows[$id]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,10 @@ final class ModuleRegistryTest extends TestCase
|
||||
'id' => 'testmod',
|
||||
'version' => '1.0.0',
|
||||
'load_order' => 10,
|
||||
'permissions' => ['test.view', 'test.edit'],
|
||||
'permissions' => [
|
||||
['key' => 'test.view', 'description' => 'Test view'],
|
||||
['key' => 'test.edit', 'description' => 'Test edit'],
|
||||
],
|
||||
'search_resources' => [],
|
||||
]);
|
||||
|
||||
@@ -51,7 +54,7 @@ final class ModuleRegistryTest extends TestCase
|
||||
|
||||
self::assertTrue($registry->hasModule('testmod'));
|
||||
self::assertSame('1.0.0', $registry->getModule('testmod')->version);
|
||||
self::assertSame(['test.view', 'test.edit'], $registry->getPermissions());
|
||||
self::assertSame(['test.view', 'test.edit'], $registry->getPermissionKeys());
|
||||
}
|
||||
|
||||
public function testDeterministicOrdering(): void
|
||||
@@ -80,8 +83,16 @@ final class ModuleRegistryTest extends TestCase
|
||||
|
||||
public function testPermissionConflictThrows(): void
|
||||
{
|
||||
$this->createModuleManifest('mod-a', ['id' => 'mod-a', 'load_order' => 1, 'permissions' => ['shared.perm']]);
|
||||
$this->createModuleManifest('mod-b', ['id' => 'mod-b', 'load_order' => 2, 'permissions' => ['shared.perm']]);
|
||||
$this->createModuleManifest('mod-a', [
|
||||
'id' => 'mod-a',
|
||||
'load_order' => 1,
|
||||
'permissions' => [['key' => 'shared.perm', 'description' => 'Shared permission']],
|
||||
]);
|
||||
$this->createModuleManifest('mod-b', [
|
||||
'id' => 'mod-b',
|
||||
'load_order' => 2,
|
||||
'permissions' => [['key' => 'shared.perm', 'description' => 'Shared permission duplicate']],
|
||||
]);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage("Permission conflict: 'shared.perm'");
|
||||
@@ -108,6 +119,137 @@ final class ModuleRegistryTest extends TestCase
|
||||
ModuleRegistry::boot($this->fixturesDir, ['mod-a', 'mod-b']);
|
||||
}
|
||||
|
||||
public function testRoutePathConflictThrows(): void
|
||||
{
|
||||
$this->createModuleManifest('mod-a', [
|
||||
'id' => 'mod-a',
|
||||
'load_order' => 1,
|
||||
'routes' => [['path' => '/shared-path', 'target' => 'a/index']],
|
||||
]);
|
||||
$this->createModuleManifest('mod-b', [
|
||||
'id' => 'mod-b',
|
||||
'load_order' => 2,
|
||||
'routes' => [['path' => '/shared-path', 'target' => 'b/index']],
|
||||
]);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage('Route path conflict');
|
||||
|
||||
ModuleRegistry::boot($this->fixturesDir, ['mod-a', 'mod-b']);
|
||||
}
|
||||
|
||||
public function testUiSlotConflictThrows(): void
|
||||
{
|
||||
$panelTemplateA = $this->createFixtureFile('mod-a-panel.phtml', '<ul></ul>');
|
||||
$panelTemplateB = $this->createFixtureFile('mod-b-panel.phtml', '<ul></ul>');
|
||||
|
||||
$this->createModuleManifest('mod-a', [
|
||||
'id' => 'mod-a',
|
||||
'load_order' => 1,
|
||||
'ui_slots' => [
|
||||
'aside.tab_panel' => [
|
||||
[
|
||||
'key' => 'people',
|
||||
'label' => 'People',
|
||||
'icon' => 'bi-people',
|
||||
'permission' => 'can_view_people',
|
||||
'panel_template' => $panelTemplateA,
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$this->createModuleManifest('mod-b', [
|
||||
'id' => 'mod-b',
|
||||
'load_order' => 2,
|
||||
'ui_slots' => [
|
||||
'aside.tab_panel' => [
|
||||
[
|
||||
'key' => 'people',
|
||||
'label' => 'People B',
|
||||
'icon' => 'bi-people',
|
||||
'permission' => 'can_view_people',
|
||||
'panel_template' => $panelTemplateB,
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage("UI slot conflict: slot 'aside.tab_panel' key 'people'");
|
||||
|
||||
ModuleRegistry::boot($this->fixturesDir, ['mod-a', 'mod-b']);
|
||||
}
|
||||
|
||||
public function testInvalidRouteContractThrows(): void
|
||||
{
|
||||
$this->createModuleManifest('mod-a', [
|
||||
'id' => 'mod-a',
|
||||
'routes' => [['path' => '', 'target' => 'address-book/index']],
|
||||
]);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage("must define non-empty 'path' and 'target'");
|
||||
|
||||
ModuleRegistry::boot($this->fixturesDir, ['mod-a']);
|
||||
}
|
||||
|
||||
public function testInvalidUiSlotContractThrows(): void
|
||||
{
|
||||
$this->createModuleManifest('mod-a', [
|
||||
'id' => 'mod-a',
|
||||
'ui_slots' => [
|
||||
'aside.tab_panel' => [
|
||||
['label' => 'Missing Key'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage("must define a non-empty 'key'");
|
||||
|
||||
ModuleRegistry::boot($this->fixturesDir, ['mod-a']);
|
||||
}
|
||||
|
||||
public function testUiSlotsAreSortedDeterministicallyByOrderModuleAndKey(): void
|
||||
{
|
||||
$this->createModuleManifest('mod-z', [
|
||||
'id' => 'mod-z',
|
||||
'load_order' => 1,
|
||||
'ui_slots' => [
|
||||
'search.resource_item' => [
|
||||
['key' => 'z-second', 'label' => 'Z Second', 'base_url' => 'z-second', 'permission' => 'can.z', 'order' => 20],
|
||||
['key' => 'z-first', 'label' => 'Z First', 'base_url' => 'z-first', 'permission' => 'can.z', 'order' => 20],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$this->createModuleManifest('mod-a', [
|
||||
'id' => 'mod-a',
|
||||
'load_order' => 1,
|
||||
'ui_slots' => [
|
||||
'search.resource_item' => [
|
||||
['key' => 'a-mid', 'label' => 'A Mid', 'base_url' => 'a-mid', 'permission' => 'can.a', 'order' => 20],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$this->createModuleManifest('mod-b', [
|
||||
'id' => 'mod-b',
|
||||
'load_order' => 1,
|
||||
'ui_slots' => [
|
||||
'search.resource_item' => [
|
||||
['key' => 'b-low', 'label' => 'B Low', 'base_url' => 'b-low', 'permission' => 'can.b', 'order' => 10],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$registry = ModuleRegistry::boot($this->fixturesDir, ['mod-z', 'mod-b', 'mod-a']);
|
||||
$slotItems = $registry->getSlotContributions('search.resource_item');
|
||||
|
||||
self::assertSame(['b-low', 'a-mid', 'z-first', 'z-second'], array_column($slotItems, 'key'));
|
||||
foreach ($slotItems as $slotItem) {
|
||||
self::assertArrayNotHasKey('__module_id', $slotItem);
|
||||
}
|
||||
}
|
||||
|
||||
public function testMissingManifestFileThrows(): void
|
||||
{
|
||||
$this->expectException(RuntimeException::class);
|
||||
@@ -126,16 +268,21 @@ final class ModuleRegistryTest extends TestCase
|
||||
ModuleRegistry::boot($this->fixturesDir, ['wrongdir']);
|
||||
}
|
||||
|
||||
public function testResolveEnabledModulesFromConfig(): void
|
||||
public function testResolveEnabledModulesFromConfigWhenEnvUnset(): void
|
||||
{
|
||||
$result = ModuleRegistry::resolveEnabledModules([
|
||||
'enabled_modules' => ['mod-a', 'mod-b'],
|
||||
]);
|
||||
putenv('APP_ENABLED_MODULES');
|
||||
try {
|
||||
$result = ModuleRegistry::resolveEnabledModules([
|
||||
'enabled_modules' => ['mod-a', 'mod-b'],
|
||||
]);
|
||||
|
||||
self::assertSame(['mod-a', 'mod-b'], $result);
|
||||
self::assertSame(['mod-a', 'mod-b'], $result);
|
||||
} finally {
|
||||
putenv('APP_ENABLED_MODULES');
|
||||
}
|
||||
}
|
||||
|
||||
public function testResolveEnabledModulesFromEnv(): void
|
||||
public function testResolveEnabledModulesFromEnvList(): void
|
||||
{
|
||||
putenv('APP_ENABLED_MODULES=env-a,env-b');
|
||||
|
||||
@@ -149,13 +296,32 @@ final class ModuleRegistryTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function testResolveEnabledModulesFromEmptyEnvReturnsNoModules(): void
|
||||
{
|
||||
putenv('APP_ENABLED_MODULES=');
|
||||
|
||||
try {
|
||||
$result = ModuleRegistry::resolveEnabledModules([
|
||||
'enabled_modules' => ['config-a', 'config-b'],
|
||||
]);
|
||||
self::assertSame([], $result);
|
||||
} finally {
|
||||
putenv('APP_ENABLED_MODULES');
|
||||
}
|
||||
}
|
||||
|
||||
public function testResolveEnabledModulesDeduplicates(): void
|
||||
{
|
||||
$result = ModuleRegistry::resolveEnabledModules([
|
||||
'enabled_modules' => ['mod-a', 'mod-a', 'mod-b'],
|
||||
]);
|
||||
putenv('APP_ENABLED_MODULES');
|
||||
try {
|
||||
$result = ModuleRegistry::resolveEnabledModules([
|
||||
'enabled_modules' => ['mod-a', 'mod-a', 'mod-b'],
|
||||
]);
|
||||
|
||||
self::assertSame(['mod-a', 'mod-b'], $result);
|
||||
self::assertSame(['mod-a', 'mod-b'], $result);
|
||||
} finally {
|
||||
putenv('APP_ENABLED_MODULES');
|
||||
}
|
||||
}
|
||||
|
||||
public function testGetNonExistentModuleThrows(): void
|
||||
@@ -212,6 +378,17 @@ final class ModuleRegistryTest extends TestCase
|
||||
);
|
||||
}
|
||||
|
||||
private function createFixtureFile(string $relativePath, string $content): string
|
||||
{
|
||||
$path = $this->fixturesDir . '/' . ltrim($relativePath, '/');
|
||||
$dir = dirname($path);
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0777, true);
|
||||
}
|
||||
file_put_contents($path, $content);
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function removeDir(string $dir): void
|
||||
{
|
||||
if (!is_dir($dir)) {
|
||||
|
||||
142
tests/App/Module/ModuleRuntimeAssetPublisherTest.php
Normal file
142
tests/App/Module/ModuleRuntimeAssetPublisherTest.php
Normal file
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\App\Module;
|
||||
|
||||
use MintyPHP\App\Module\ModuleManifest;
|
||||
use MintyPHP\App\Module\ModuleRuntimeAssetPublisher;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ModuleRuntimeAssetPublisherTest extends TestCase
|
||||
{
|
||||
private string $tmpDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->tmpDir = sys_get_temp_dir() . '/corecore-module-assets-test-' . uniqid();
|
||||
mkdir($this->tmpDir, 0777, true);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->removePath($this->tmpDir);
|
||||
}
|
||||
|
||||
public function testPublishSymlinkCreatesManagedModuleLinksAndRemovesStaleEntries(): void
|
||||
{
|
||||
if (!function_exists('symlink')) {
|
||||
self::markTestSkipped('Symlink support is required for this test.');
|
||||
}
|
||||
|
||||
$moduleA = $this->createModuleWithWebAssets('module-a', ['js/a.js' => 'console.log("a");']);
|
||||
$moduleB = $this->createModuleWithoutWebAssets('module-b');
|
||||
$runtimeModulesDir = $this->tmpDir . '/web/modules';
|
||||
mkdir($runtimeModulesDir, 0777, true);
|
||||
file_put_contents($runtimeModulesDir . '/stale.txt', 'old');
|
||||
|
||||
$publisher = new ModuleRuntimeAssetPublisher();
|
||||
$result = $publisher->publish($runtimeModulesDir, [
|
||||
'module-a' => $moduleA,
|
||||
'module-b' => $moduleB,
|
||||
], 'symlink');
|
||||
|
||||
self::assertTrue(is_link($runtimeModulesDir . '/module-a'));
|
||||
self::assertSame(
|
||||
realpath($this->tmpDir . '/modules/module-a/web'),
|
||||
realpath($runtimeModulesDir . '/module-a')
|
||||
);
|
||||
self::assertFileDoesNotExist($runtimeModulesDir . '/module-b');
|
||||
self::assertFileDoesNotExist($runtimeModulesDir . '/stale.txt');
|
||||
self::assertSame(1, $result['created']);
|
||||
self::assertSame(1, $result['removed']);
|
||||
}
|
||||
|
||||
public function testPublishSymlinkUpdatesWrongExistingLink(): void
|
||||
{
|
||||
if (!function_exists('symlink')) {
|
||||
self::markTestSkipped('Symlink support is required for this test.');
|
||||
}
|
||||
|
||||
$moduleA = $this->createModuleWithWebAssets('module-a', ['css/a.css' => '.a{}']);
|
||||
$runtimeModulesDir = $this->tmpDir . '/web/modules';
|
||||
mkdir($runtimeModulesDir, 0777, true);
|
||||
|
||||
$wrongTarget = $this->tmpDir . '/wrong-target';
|
||||
mkdir($wrongTarget, 0777, true);
|
||||
symlink($wrongTarget, $runtimeModulesDir . '/module-a');
|
||||
|
||||
$publisher = new ModuleRuntimeAssetPublisher();
|
||||
$result = $publisher->publish($runtimeModulesDir, ['module-a' => $moduleA], 'symlink');
|
||||
|
||||
self::assertTrue(is_link($runtimeModulesDir . '/module-a'));
|
||||
self::assertSame(
|
||||
realpath($this->tmpDir . '/modules/module-a/web'),
|
||||
realpath($runtimeModulesDir . '/module-a')
|
||||
);
|
||||
self::assertSame(1, $result['updated']);
|
||||
}
|
||||
|
||||
public function testPublishCopyModeCopiesModuleAssets(): void
|
||||
{
|
||||
$moduleA = $this->createModuleWithWebAssets('module-a', [
|
||||
'js/app.js' => 'console.log("copy-mode");',
|
||||
'css/app.css' => '.copy-mode{}',
|
||||
]);
|
||||
$runtimeModulesDir = $this->tmpDir . '/web/modules';
|
||||
|
||||
$publisher = new ModuleRuntimeAssetPublisher();
|
||||
$result = $publisher->publish($runtimeModulesDir, ['module-a' => $moduleA], 'copy');
|
||||
|
||||
self::assertDirectoryExists($runtimeModulesDir . '/module-a');
|
||||
self::assertFalse(is_link($runtimeModulesDir . '/module-a'));
|
||||
self::assertFileExists($runtimeModulesDir . '/module-a/js/app.js');
|
||||
self::assertFileExists($runtimeModulesDir . '/module-a/css/app.css');
|
||||
self::assertSame(1, $result['created']);
|
||||
}
|
||||
|
||||
private function createModuleWithWebAssets(string $id, array $files): ModuleManifest
|
||||
{
|
||||
$moduleDir = $this->tmpDir . '/modules/' . $id;
|
||||
mkdir($moduleDir . '/web', 0777, true);
|
||||
foreach ($files as $relativePath => $content) {
|
||||
$target = $moduleDir . '/web/' . ltrim($relativePath, '/');
|
||||
$targetDir = dirname($target);
|
||||
if (!is_dir($targetDir)) {
|
||||
mkdir($targetDir, 0777, true);
|
||||
}
|
||||
file_put_contents($target, $content);
|
||||
}
|
||||
|
||||
return ModuleManifest::fromArray(['id' => $id], $moduleDir);
|
||||
}
|
||||
|
||||
private function createModuleWithoutWebAssets(string $id): ModuleManifest
|
||||
{
|
||||
$moduleDir = $this->tmpDir . '/modules/' . $id;
|
||||
mkdir($moduleDir, 0777, true);
|
||||
return ModuleManifest::fromArray(['id' => $id], $moduleDir);
|
||||
}
|
||||
|
||||
private function removePath(string $path): void
|
||||
{
|
||||
if (!file_exists($path) && !is_link($path)) {
|
||||
return;
|
||||
}
|
||||
if (is_link($path) || is_file($path)) {
|
||||
@unlink($path);
|
||||
return;
|
||||
}
|
||||
if (!is_dir($path)) {
|
||||
return;
|
||||
}
|
||||
$entries = scandir($path);
|
||||
if ($entries !== false) {
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry === '.' || $entry === '..') {
|
||||
continue;
|
||||
}
|
||||
$this->removePath($path . '/' . $entry);
|
||||
}
|
||||
}
|
||||
@rmdir($path);
|
||||
}
|
||||
}
|
||||
55
tests/App/Module/RouterConfigCollisionTest.php
Normal file
55
tests/App/Module/RouterConfigCollisionTest.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\App\Module;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
use MintyPHP\App\Module\ModuleRegistry;
|
||||
use MintyPHP\Tests\Support\AppContainerIsolationTrait;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class RouterConfigCollisionTest extends TestCase
|
||||
{
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
/**
|
||||
* @runInSeparateProcess
|
||||
*/
|
||||
public function testModuleRoutePathCollidingWithCoreRouteThrows(): void
|
||||
{
|
||||
$fixturesDir = sys_get_temp_dir() . '/router-config-collision-' . uniqid();
|
||||
mkdir($fixturesDir . '/mod-a', 0777, true);
|
||||
file_put_contents(
|
||||
$fixturesDir . '/mod-a/module.php',
|
||||
'<?php return ' . var_export([
|
||||
'id' => 'mod-a',
|
||||
'routes' => [
|
||||
['path' => 'login', 'target' => 'mod-a/login'],
|
||||
],
|
||||
], true) . ';'
|
||||
);
|
||||
|
||||
try {
|
||||
$registry = ModuleRegistry::boot($fixturesDir, ['mod-a']);
|
||||
|
||||
$container = new AppContainer();
|
||||
$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';
|
||||
} finally {
|
||||
$this->restoreAppContainer();
|
||||
@unlink($fixturesDir . '/mod-a/module.php');
|
||||
@rmdir($fixturesDir . '/mod-a');
|
||||
@rmdir($fixturesDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
34
tests/Architecture/AppContainerIsolationContractTest.php
Normal file
34
tests/Architecture/AppContainerIsolationContractTest.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Architecture;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Contract: Direct writes to $GLOBALS['minty_app_container'] are only allowed
|
||||
* inside the dedicated AppContainerIsolationTrait.
|
||||
*/
|
||||
final class AppContainerIsolationContractTest extends TestCase
|
||||
{
|
||||
use ProjectFileAssertionSupport;
|
||||
|
||||
public function testDirectAppContainerGlobalWritesAreRestrictedToIsolationTrait(): void
|
||||
{
|
||||
$violations = array_merge(
|
||||
$this->findPatternMatchesInPhpFiles('tests', '/\\$GLOBALS\\[\'minty_app_container\'\\]\\s*=/'),
|
||||
$this->findPatternMatchesInPhpFiles('tests', '/unset\\(\\$GLOBALS\\[\'minty_app_container\'\\]\\)/')
|
||||
);
|
||||
|
||||
$allowed = [
|
||||
'tests/Support/AppContainerIsolationTrait.php',
|
||||
];
|
||||
|
||||
$violations = array_values(array_filter(
|
||||
array_unique($violations),
|
||||
static fn (string $path): bool => !in_array($path, $allowed, true)
|
||||
));
|
||||
sort($violations);
|
||||
|
||||
self::assertSame([], $violations, "Direct global app-container writes found outside isolation trait:\n" . implode("\n", $violations));
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ class ContainerFactoryContractTest extends TestCase
|
||||
{
|
||||
return [
|
||||
[\MintyPHP\Service\Access\AccessServicesFactory::class],
|
||||
[\MintyPHP\Service\AddressBook\AddressBookServicesFactory::class],
|
||||
[\MintyPHP\Module\AddressBook\Service\AddressBookServicesFactory::class],
|
||||
[\MintyPHP\Service\Audit\AuditServicesFactory::class],
|
||||
[\MintyPHP\Service\Auth\AuthServicesFactory::class],
|
||||
[\MintyPHP\Service\Branding\BrandingServicesFactory::class],
|
||||
|
||||
58
tests/Architecture/CoreTemplateIsolationTest.php
Normal file
58
tests/Architecture/CoreTemplateIsolationTest.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Architecture;
|
||||
|
||||
use FilesystemIterator;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
|
||||
final class CoreTemplateIsolationTest extends TestCase
|
||||
{
|
||||
public function testCoreTemplatesDoNotReferenceModuleSpecificLayoutNavKeys(): void
|
||||
{
|
||||
$projectRoot = dirname(__DIR__, 2);
|
||||
$templatesDir = $projectRoot . '/templates';
|
||||
$modulesDir = $projectRoot . '/modules';
|
||||
|
||||
if (!is_dir($templatesDir) || !is_dir($modulesDir)) {
|
||||
self::markTestSkipped('templates/ or modules/ directory missing.');
|
||||
}
|
||||
|
||||
$moduleIds = [];
|
||||
foreach (scandir($modulesDir) ?: [] as $entry) {
|
||||
if ($entry === '.' || $entry === '..') {
|
||||
continue;
|
||||
}
|
||||
if (!is_dir($modulesDir . '/' . $entry)) {
|
||||
continue;
|
||||
}
|
||||
$moduleIds[] = $entry;
|
||||
}
|
||||
|
||||
$violations = [];
|
||||
$iterator = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($templatesDir, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->getExtension() !== 'phtml') {
|
||||
continue;
|
||||
}
|
||||
$path = $file->getPathname();
|
||||
$content = file_get_contents($path);
|
||||
if (!is_string($content)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($moduleIds as $moduleId) {
|
||||
if (preg_match("/layoutNav\[['\"]" . preg_quote($moduleId, '/') . "(\\.|['\"])" . "/", $content) === 1) {
|
||||
$violations[] = str_replace($projectRoot . '/', '', $path) . ' references layoutNav module key for ' . $moduleId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self::assertSame([], $violations, "Core templates reference module layout keys:\n" . implode("\n", $violations));
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,8 @@ class DetailPageContractTest extends TestCase
|
||||
public function testAppInitIncludesStandardDetailPageAutoInitComponent(): void
|
||||
{
|
||||
$content = $this->readProjectFile('web/js/app-init.js');
|
||||
$this->assertStringContainsString("import './components/app-standard-detail-page.js';", $content);
|
||||
$this->assertStringContainsString("import { initStandardDetailPages } from './components/app-standard-detail-page.js';", $content);
|
||||
$this->assertStringContainsString("runtime.register('standard-detail-page', initStandardDetailPages", $content);
|
||||
}
|
||||
|
||||
public function testDetailsTitlebarExposesUnsavedMessageAndPrimarySaveMarkers(): void
|
||||
|
||||
@@ -11,10 +11,14 @@ class FilterDrawerContractTest extends TestCase
|
||||
private function readTemplatePageModule(string $templateFile): string
|
||||
{
|
||||
$template = $this->readProjectFile($templateFile);
|
||||
$matched = preg_match("/assetVersion\\('js\\/pages\\/([^']+\\.js)'\\)/", $template, $captures);
|
||||
$matched = preg_match(
|
||||
"/assetVersion\\('((?:modules\\/[^\\/]+\\/)?js\\/pages\\/[^']+\\.js)'\\)/",
|
||||
$template,
|
||||
$captures
|
||||
);
|
||||
$this->assertSame(1, $matched, $templateFile . ' must reference a page module via assetVersion().');
|
||||
|
||||
return $this->readProjectFile('web/js/pages/' . $captures[1]);
|
||||
return $this->readProjectFile('web/' . ltrim($captures[1], '/'));
|
||||
}
|
||||
|
||||
private function usesSharedListFiltersPartial(string $content): bool
|
||||
@@ -28,7 +32,7 @@ class FilterDrawerContractTest extends TestCase
|
||||
private function drawerTemplateFiles(): array
|
||||
{
|
||||
return [
|
||||
'pages/address-book/index(default).phtml',
|
||||
'modules/addressbook/pages/address-book/index(default).phtml',
|
||||
'pages/admin/users/index(default).phtml',
|
||||
'pages/admin/tenants/index(default).phtml',
|
||||
'pages/admin/departments/index(default).phtml',
|
||||
@@ -64,8 +68,8 @@ class FilterDrawerContractTest extends TestCase
|
||||
|
||||
public function testAddressBookFilterChipsContract(): void
|
||||
{
|
||||
$content = $this->readProjectFile('pages/address-book/index(default).phtml');
|
||||
$moduleContent = $this->readProjectFile('web/js/pages/address-book-index.js');
|
||||
$content = $this->readProjectFile('modules/addressbook/pages/address-book/index(default).phtml');
|
||||
$moduleContent = $this->readProjectFile('modules/addressbook/web/js/pages/address-book-index.js');
|
||||
|
||||
$this->assertStringNotContainsString('const state = collectFilterState();', $moduleContent);
|
||||
$this->assertStringContainsString('data-filter-chips-clear-all-label', $content);
|
||||
|
||||
@@ -11,10 +11,14 @@ class ListFilterContractTest extends TestCase
|
||||
private function readTemplatePageModule(string $templateFile): string
|
||||
{
|
||||
$template = $this->readProjectFile($templateFile);
|
||||
$matched = preg_match("/assetVersion\\('js\\/pages\\/([^']+\\.js)'\\)/", $template, $captures);
|
||||
$matched = preg_match(
|
||||
"/assetVersion\\('((?:modules\\/[^\\/]+\\/)?js\\/pages\\/[^']+\\.js)'\\)/",
|
||||
$template,
|
||||
$captures
|
||||
);
|
||||
$this->assertSame(1, $matched, $templateFile . ' must reference a page module via assetVersion().');
|
||||
|
||||
return $this->readProjectFile('web/js/pages/' . $captures[1]);
|
||||
return $this->readProjectFile('web/' . ltrim($captures[1], '/'));
|
||||
}
|
||||
|
||||
private function usesSharedListFiltersPartial(string $content): bool
|
||||
@@ -28,7 +32,7 @@ class ListFilterContractTest extends TestCase
|
||||
private function hardCutGridEndpointFiles(): array
|
||||
{
|
||||
return [
|
||||
'pages/address-book/data().php',
|
||||
'modules/addressbook/pages/address-book/data().php',
|
||||
'pages/search/data().php',
|
||||
'pages/admin/users/data().php',
|
||||
'pages/admin/tenants/data().php',
|
||||
@@ -51,7 +55,7 @@ class ListFilterContractTest extends TestCase
|
||||
private function hardCutGridEndpointSchemaFiles(): array
|
||||
{
|
||||
return [
|
||||
'pages/address-book/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
|
||||
'modules/addressbook/pages/address-book/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
|
||||
'pages/search/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
|
||||
'pages/admin/users/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
|
||||
'pages/admin/tenants/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
|
||||
@@ -74,7 +78,7 @@ class ListFilterContractTest extends TestCase
|
||||
private function listIndexTemplates(): array
|
||||
{
|
||||
return [
|
||||
'pages/address-book/index(default).phtml',
|
||||
'modules/addressbook/pages/address-book/index(default).phtml',
|
||||
'pages/search/index(default).phtml',
|
||||
'pages/admin/users/index(default).phtml',
|
||||
'pages/admin/tenants/index(default).phtml',
|
||||
@@ -96,7 +100,7 @@ class ListFilterContractTest extends TestCase
|
||||
private function listIndexActions(): array
|
||||
{
|
||||
return [
|
||||
'pages/address-book/index().php',
|
||||
'modules/addressbook/pages/address-book/index().php',
|
||||
'pages/search/index().php',
|
||||
'pages/admin/users/index().php',
|
||||
'pages/admin/tenants/index().php',
|
||||
@@ -118,7 +122,7 @@ class ListFilterContractTest extends TestCase
|
||||
private function drawerListTemplates(): array
|
||||
{
|
||||
return [
|
||||
'pages/address-book/index(default).phtml',
|
||||
'modules/addressbook/pages/address-book/index(default).phtml',
|
||||
'pages/admin/users/index(default).phtml',
|
||||
'pages/admin/tenants/index(default).phtml',
|
||||
'pages/admin/departments/index(default).phtml',
|
||||
|
||||
@@ -25,7 +25,7 @@ class ListTitlebarContractTest extends TestCase
|
||||
'pages/admin/import-audit/index(default).phtml',
|
||||
'pages/admin/user-lifecycle-audit/index(default).phtml',
|
||||
'pages/admin/system-audit/index(default).phtml',
|
||||
'pages/address-book/index(default).phtml',
|
||||
'modules/addressbook/pages/address-book/index(default).phtml',
|
||||
'pages/search/index(default).phtml',
|
||||
'pages/help/hotkeys(default).phtml',
|
||||
];
|
||||
|
||||
@@ -68,6 +68,7 @@ class ListUiSharedPartialsContractTest extends TestCase
|
||||
public function testAppInitIncludesGlobalConfirmActionComponent(): void
|
||||
{
|
||||
$content = $this->readProjectFile('web/js/app-init.js');
|
||||
$this->assertStringContainsString("import './components/app-confirm-actions.js';", $content);
|
||||
$this->assertStringContainsString("import { initConfirmActions } from './components/app-confirm-actions.js';", $content);
|
||||
$this->assertStringContainsString("runtime.register('confirm-actions', initConfirmActions", $content);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ final class ModuleRegistryContractTest extends TestCase
|
||||
|
||||
public function testAddressBookModuleLoadsWhenEnabled(): void
|
||||
{
|
||||
$registry = app(ModuleRegistry::class);
|
||||
$modulesDir = dirname(__DIR__, 2) . '/modules';
|
||||
$registry = ModuleRegistry::boot($modulesDir, ['addressbook']);
|
||||
|
||||
// config/modules.php has addressbook enabled by default
|
||||
self::assertTrue($registry->hasModule('addressbook'));
|
||||
self::assertNotEmpty($registry->getSearchResources());
|
||||
self::assertNotEmpty($registry->getLayoutContextProviders());
|
||||
@@ -32,8 +32,16 @@ final class ModuleRegistryContractTest extends TestCase
|
||||
{
|
||||
$modulesDir = dirname(__DIR__, 2) . '/modules';
|
||||
|
||||
// Boot a fresh registry with no modules enabled (simulates APP_ENABLED_MODULES='')
|
||||
$registry = ModuleRegistry::boot($modulesDir, []);
|
||||
putenv('APP_ENABLED_MODULES=');
|
||||
try {
|
||||
$enabledModules = ModuleRegistry::resolveEnabledModules([
|
||||
'enabled_modules' => ['addressbook', 'bookmarks'],
|
||||
]);
|
||||
self::assertSame([], $enabledModules, 'APP_ENABLED_MODULES empty string must disable all modules.');
|
||||
$registry = ModuleRegistry::boot($modulesDir, $enabledModules);
|
||||
} finally {
|
||||
putenv('APP_ENABLED_MODULES');
|
||||
}
|
||||
|
||||
self::assertSame([], $registry->getModules());
|
||||
self::assertSame([], $registry->getRoutes());
|
||||
@@ -54,14 +62,53 @@ final class ModuleRegistryContractTest extends TestCase
|
||||
$raw = require $manifestFile;
|
||||
self::assertIsArray($raw);
|
||||
self::assertSame('addressbook', $raw['id']);
|
||||
// Permissions owned by Core PermissionService, not module
|
||||
self::assertSame([], $raw['permissions']);
|
||||
// Asset groups owned by config/assets.php, not module
|
||||
self::assertSame([], $raw['asset_groups']);
|
||||
self::assertSame([[
|
||||
'key' => 'address_book.view',
|
||||
'description' => 'Can view address book',
|
||||
'active' => true,
|
||||
'is_system' => true,
|
||||
]], $raw['permissions']);
|
||||
self::assertArrayHasKey('address-book', $raw['asset_groups']);
|
||||
self::assertSame(
|
||||
['modules/addressbook/css/pages/address-book-view.css'],
|
||||
$raw['asset_groups']['address-book']
|
||||
);
|
||||
self::assertNotEmpty($raw['search_resources']);
|
||||
self::assertNotEmpty($raw['layout_context_providers']);
|
||||
self::assertNotEmpty($raw['session_providers']);
|
||||
self::assertArrayHasKey('aside.tab_panel', $raw['ui_slots']);
|
||||
self::assertArrayHasKey('search.resource_item', $raw['ui_slots']);
|
||||
self::assertArrayHasKey('user.edit.aside_action', $raw['ui_slots']);
|
||||
|
||||
$routes = is_array($raw['routes'] ?? null) ? $raw['routes'] : [];
|
||||
$routeByPath = [];
|
||||
foreach ($routes as $route) {
|
||||
if (!is_array($route)) {
|
||||
continue;
|
||||
}
|
||||
$routeByPath[(string) ($route['path'] ?? '')] = (string) ($route['target'] ?? '');
|
||||
}
|
||||
self::assertSame('address-book', $routeByPath['address-book'] ?? null);
|
||||
self::assertSame('address-book/data', $routeByPath['address-book/data'] ?? null);
|
||||
self::assertSame('address-book', $routeByPath['addressbook'] ?? null);
|
||||
self::assertSame('address-book', $routeByPath['adressbook'] ?? null);
|
||||
}
|
||||
|
||||
public function testBookmarksModuleManifestIsValid(): void
|
||||
{
|
||||
$modulesDir = dirname(__DIR__, 2) . '/modules';
|
||||
$manifestFile = $modulesDir . '/bookmarks/module.php';
|
||||
|
||||
self::assertFileExists($manifestFile, 'Bookmarks module manifest must exist');
|
||||
|
||||
$raw = require $manifestFile;
|
||||
self::assertIsArray($raw);
|
||||
self::assertSame('bookmarks', $raw['id']);
|
||||
self::assertArrayHasKey('aside.tab_panel', $raw['ui_slots']);
|
||||
self::assertArrayHasKey('topbar.right_item', $raw['ui_slots']);
|
||||
self::assertArrayHasKey('layout.body_end_template', $raw['ui_slots']);
|
||||
self::assertArrayHasKey('layout.head_style', $raw['ui_slots']);
|
||||
self::assertArrayHasKey('runtime.component', $raw['ui_slots']);
|
||||
}
|
||||
|
||||
public function testModuleProviderClassesExist(): void
|
||||
@@ -104,11 +151,11 @@ final class ModuleRegistryContractTest extends TestCase
|
||||
|
||||
file_put_contents($fixturesDir . '/mod-a/module.php', '<?php return ' . var_export([
|
||||
'id' => 'mod-a',
|
||||
'permissions' => ['shared.perm'],
|
||||
'permissions' => [['key' => 'shared.perm', 'description' => 'Shared']],
|
||||
], true) . ';');
|
||||
file_put_contents($fixturesDir . '/mod-b/module.php', '<?php return ' . var_export([
|
||||
'id' => 'mod-b',
|
||||
'permissions' => ['shared.perm'],
|
||||
'permissions' => [['key' => 'shared.perm', 'description' => 'Shared duplicate']],
|
||||
], true) . ';');
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
|
||||
576
tests/Architecture/ModuleStructureContractTest.php
Normal file
576
tests/Architecture/ModuleStructureContractTest.php
Normal file
@@ -0,0 +1,576 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Architecture;
|
||||
|
||||
use MintyPHP\App\Module\Contracts\LayoutContextProvider;
|
||||
use MintyPHP\App\Module\Contracts\SearchResourceProvider;
|
||||
use MintyPHP\App\Module\Contracts\SessionProvider;
|
||||
use MintyPHP\App\Module\ModuleManifest;
|
||||
use MintyPHP\Service\Access\AuthorizationPolicyInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Architecture test: enforces structural conventions for ALL modules under modules/.
|
||||
*
|
||||
* Every module directory must pass these checks. This ensures consistency
|
||||
* when new modules are added and prevents structural drift.
|
||||
*/
|
||||
final class ModuleStructureContractTest extends TestCase
|
||||
{
|
||||
use ProjectFileAssertionSupport;
|
||||
|
||||
/** @var list<array{id: string, path: string, manifest: ModuleManifest, raw: array<string, mixed>}> */
|
||||
private static array $modules = [];
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
$modulesDir = realpath(__DIR__ . '/../../modules');
|
||||
if ($modulesDir === false || !is_dir($modulesDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$entries = scandir($modulesDir);
|
||||
if ($entries === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry === '.' || $entry === '..' || !is_dir($modulesDir . '/' . $entry)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$manifestFile = $modulesDir . '/' . $entry . '/module.php';
|
||||
if (!is_file($manifestFile)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$raw = require $manifestFile;
|
||||
if (!is_array($raw)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$manifest = ModuleManifest::fromArray($raw, $modulesDir . '/' . $entry);
|
||||
self::$modules[] = [
|
||||
'id' => $entry,
|
||||
'path' => $modulesDir . '/' . $entry,
|
||||
'manifest' => $manifest,
|
||||
'raw' => $raw,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Manifest structure ──────────────────────────────────────────
|
||||
|
||||
public function testAtLeastOneModuleExists(): void
|
||||
{
|
||||
self::assertNotEmpty(self::$modules, 'Expected at least one module under modules/');
|
||||
}
|
||||
|
||||
public function testEveryModuleHasManifest(): void
|
||||
{
|
||||
$modulesDir = $this->projectRootPath() . '/modules';
|
||||
if (!is_dir($modulesDir)) {
|
||||
self::markTestSkipped('No modules/ directory');
|
||||
}
|
||||
|
||||
$entries = scandir($modulesDir) ?: [];
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry === '.' || $entry === '..' || !is_dir($modulesDir . '/' . $entry)) {
|
||||
continue;
|
||||
}
|
||||
self::assertFileExists(
|
||||
$modulesDir . '/' . $entry . '/module.php',
|
||||
"Module directory '{$entry}' is missing module.php manifest"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function testManifestIdMatchesDirectoryName(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
self::assertSame(
|
||||
$module['id'],
|
||||
$module['manifest']->id,
|
||||
"Module directory '{$module['id']}' has mismatched manifest id '{$module['manifest']->id}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function testManifestHasVersion(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
self::assertMatchesRegularExpression(
|
||||
'/^\d+\.\d+\.\d+$/',
|
||||
$module['manifest']->version,
|
||||
"Module '{$module['id']}' must have a semver version (got '{$module['manifest']->version}')"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function testManifestHasAllRequiredKeys(): void
|
||||
{
|
||||
$requiredKeys = [
|
||||
'id', 'version', 'enabled_by_default', 'load_order',
|
||||
'routes', 'public_paths', 'container_registrars',
|
||||
'ui_slots', 'search_resources', 'asset_groups',
|
||||
'scheduler_jobs', 'layout_context_providers',
|
||||
'session_providers', 'permissions',
|
||||
];
|
||||
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($requiredKeys as $key) {
|
||||
self::assertArrayHasKey(
|
||||
$key,
|
||||
$module['raw'],
|
||||
"Module '{$module['id']}' manifest is missing required key '{$key}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── File structure ──────────────────────────────────────────────
|
||||
|
||||
public function testModuleHasLibDirectory(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
self::assertDirectoryExists(
|
||||
$module['path'] . '/lib',
|
||||
"Module '{$module['id']}' must have a lib/ directory for PHP classes"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Container registrars ────────────────────────────────────────
|
||||
|
||||
public function testContainerRegistrarClassesExist(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->containerRegistrars as $registrar) {
|
||||
self::assertTrue(
|
||||
class_exists($registrar),
|
||||
"Module '{$module['id']}' declares container_registrar '{$registrar}' but class does not exist"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Provider contracts ──────────────────────────────────────────
|
||||
|
||||
public function testSearchProviderClassesImplementContract(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->searchResources as $providerClass) {
|
||||
self::assertTrue(
|
||||
class_exists($providerClass),
|
||||
"Module '{$module['id']}' search provider '{$providerClass}' class not found"
|
||||
);
|
||||
$provider = new $providerClass();
|
||||
self::assertInstanceOf(
|
||||
SearchResourceProvider::class,
|
||||
$provider,
|
||||
"Module '{$module['id']}' search provider must implement SearchResourceProvider"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function testLayoutContextProviderClassesImplementContract(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->layoutContextProviders as $providerClass) {
|
||||
self::assertTrue(
|
||||
class_exists($providerClass),
|
||||
"Module '{$module['id']}' layout context provider '{$providerClass}' class not found"
|
||||
);
|
||||
$provider = new $providerClass();
|
||||
self::assertInstanceOf(
|
||||
LayoutContextProvider::class,
|
||||
$provider,
|
||||
"Module '{$module['id']}' layout context provider must implement LayoutContextProvider"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function testSessionProviderClassesImplementContract(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->sessionProviders as $providerClass) {
|
||||
self::assertTrue(
|
||||
class_exists($providerClass),
|
||||
"Module '{$module['id']}' session provider '{$providerClass}' class not found"
|
||||
);
|
||||
$provider = new $providerClass();
|
||||
self::assertInstanceOf(
|
||||
SessionProvider::class,
|
||||
$provider,
|
||||
"Module '{$module['id']}' session provider must implement SessionProvider"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Authorization policies ──────────────────────────────────────
|
||||
|
||||
public function testAuthorizationPolicyClassesImplementContract(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->authorizationPolicies as $policyClass) {
|
||||
self::assertTrue(
|
||||
class_exists($policyClass),
|
||||
"Module '{$module['id']}' authorization policy '{$policyClass}' class not found"
|
||||
);
|
||||
self::assertTrue(
|
||||
is_subclass_of($policyClass, AuthorizationPolicyInterface::class)
|
||||
|| in_array(AuthorizationPolicyInterface::class, class_implements($policyClass) ?: [], true),
|
||||
"Module '{$module['id']}' authorization policy must implement AuthorizationPolicyInterface"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Layout capabilities ─────────────────────────────────────────
|
||||
|
||||
public function testLayoutCapabilitiesHaveNonEmptyKeysAndAbilities(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->layoutCapabilities as $uiKey => $ability) {
|
||||
self::assertNotEmpty(
|
||||
trim((string) $uiKey),
|
||||
"Module '{$module['id']}' has empty layout_capabilities key"
|
||||
);
|
||||
self::assertNotEmpty(
|
||||
trim((string) $ability),
|
||||
"Module '{$module['id']}' layout_capabilities key '{$uiKey}' has empty ability"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function testLayoutCapabilityAbilitiesMatchPolicySupports(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
if (empty($module['manifest']->layoutCapabilities)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Collect all abilities supported by this module's policies
|
||||
$supportedAbilities = [];
|
||||
foreach ($module['manifest']->authorizationPolicies as $policyClass) {
|
||||
if (!class_exists($policyClass)) {
|
||||
continue;
|
||||
}
|
||||
// Check each layout capability ability against this policy
|
||||
$reflection = new \ReflectionClass($policyClass);
|
||||
foreach ($reflection->getConstants() as $constValue) {
|
||||
if (is_string($constValue)) {
|
||||
$supportedAbilities[] = $constValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($module['manifest']->layoutCapabilities as $uiKey => $ability) {
|
||||
self::assertContains(
|
||||
$ability,
|
||||
$supportedAbilities,
|
||||
"Module '{$module['id']}' layout_capabilities['{$uiKey}'] references ability '{$ability}' "
|
||||
. "but no module authorization policy declares it as a constant"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Permissions contract ───────────────────────────────────────
|
||||
|
||||
public function testPermissionsUseObjectContract(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->permissions as $index => $permission) {
|
||||
self::assertArrayHasKey('key', $permission, "Module '{$module['id']}' permissions[{$index}] missing key");
|
||||
self::assertArrayHasKey('description', $permission, "Module '{$module['id']}' permissions[{$index}] missing description");
|
||||
self::assertNotEmpty(trim((string) $permission['key']), "Module '{$module['id']}' permissions[{$index}] key must be non-empty");
|
||||
self::assertNotEmpty(trim((string) $permission['description']), "Module '{$module['id']}' permissions[{$index}] description must be non-empty");
|
||||
self::assertContains((int) $permission['active'], [0, 1], "Module '{$module['id']}' permissions[{$index}] active must be 0|1");
|
||||
self::assertContains((int) $permission['is_system'], [0, 1], "Module '{$module['id']}' permissions[{$index}] is_system must be 0|1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Scheduler jobs contract ────────────────────────────────────
|
||||
|
||||
public function testSchedulerJobsUseFullContractSchema(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->schedulerJobs as $index => $job) {
|
||||
$required = [
|
||||
'job_key',
|
||||
'handler',
|
||||
'label',
|
||||
'description',
|
||||
'default_enabled',
|
||||
'default_timezone',
|
||||
'default_schedule_type',
|
||||
'default_schedule_interval',
|
||||
'default_schedule_time',
|
||||
'default_schedule_weekdays_csv',
|
||||
'default_catchup_once',
|
||||
'allowed_schedule_types',
|
||||
];
|
||||
|
||||
foreach ($required as $requiredKey) {
|
||||
self::assertArrayHasKey(
|
||||
$requiredKey,
|
||||
$job,
|
||||
"Module '{$module['id']}' scheduler_jobs[{$index}] missing '{$requiredKey}'"
|
||||
);
|
||||
}
|
||||
|
||||
self::assertNotEmpty(trim((string) $job['job_key']), "Module '{$module['id']}' scheduler_jobs[{$index}] job_key must be non-empty");
|
||||
self::assertNotEmpty(trim((string) $job['handler']), "Module '{$module['id']}' scheduler_jobs[{$index}] handler must be non-empty");
|
||||
self::assertNotEmpty(trim((string) $job['label']), "Module '{$module['id']}' scheduler_jobs[{$index}] label must be non-empty");
|
||||
self::assertContains(
|
||||
(string) $job['default_schedule_type'],
|
||||
['hourly', 'daily', 'weekly'],
|
||||
"Module '{$module['id']}' scheduler_jobs[{$index}] default_schedule_type invalid"
|
||||
);
|
||||
|
||||
$allowedTypes = array_values($job['allowed_schedule_types']);
|
||||
self::assertNotEmpty($allowedTypes, "Module '{$module['id']}' scheduler_jobs[{$index}] allowed_schedule_types must be non-empty");
|
||||
foreach ($allowedTypes as $allowedType) {
|
||||
self::assertContains(
|
||||
(string) $allowedType,
|
||||
['hourly', 'daily', 'weekly'],
|
||||
"Module '{$module['id']}' scheduler_jobs[{$index}] allowed_schedule_types entry invalid"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self::addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── UI slots ────────────────────────────────────────────────────
|
||||
|
||||
public function testUiSlotContributionsHaveRequiredKeys(): void
|
||||
{
|
||||
$slotKeyRequirements = [
|
||||
'aside.tab_panel' => ['key', 'label', 'icon', 'permission', 'panel_template'],
|
||||
'search.resource_item' => ['key', 'label', 'base_url', 'permission'],
|
||||
'user.edit.aside_action' => ['key', 'type', 'label', 'permission'],
|
||||
'topbar.right_item' => ['key', 'template'],
|
||||
'layout.body_end_template' => ['key', 'template'],
|
||||
'layout.head_style' => ['key', 'path'],
|
||||
'runtime.component' => ['key', 'script'],
|
||||
];
|
||||
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->uiSlots as $slotName => $contributions) {
|
||||
if (!isset($slotKeyRequirements[$slotName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$required = $slotKeyRequirements[$slotName];
|
||||
$contributionList = is_array($contributions) ? $contributions : [$contributions];
|
||||
|
||||
foreach ($contributionList as $idx => $contribution) {
|
||||
if (!is_array($contribution)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($required as $requiredKey) {
|
||||
self::assertArrayHasKey(
|
||||
$requiredKey,
|
||||
$contribution,
|
||||
"Module '{$module['id']}' ui_slots['{$slotName}'][{$idx}] is missing required key '{$requiredKey}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function testPanelTemplatesExist(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
$templateSlots = [
|
||||
'aside.tab_panel' => 'panel_template',
|
||||
'topbar.right_item' => 'template',
|
||||
'layout.body_end_template' => 'template',
|
||||
];
|
||||
|
||||
foreach ($templateSlots as $slotName => $templateKey) {
|
||||
$contributions = $module['manifest']->uiSlots[$slotName] ?? [];
|
||||
if (!is_array($contributions)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($contributions as $contribution) {
|
||||
if (!is_array($contribution)) {
|
||||
continue;
|
||||
}
|
||||
$template = $contribution[$templateKey] ?? null;
|
||||
if ($template === null) {
|
||||
continue;
|
||||
}
|
||||
self::assertFileExists(
|
||||
(string) $template,
|
||||
"Module '{$module['id']}' {$slotName} {$templateKey} does not exist: {$template}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function testRuntimeComponentPhasesAreValid(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
$runtimeComponents = $module['manifest']->uiSlots['runtime.component'] ?? [];
|
||||
if (!is_array($runtimeComponents)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($runtimeComponents as $index => $contribution) {
|
||||
if (!is_array($contribution)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$phase = strtolower(trim((string) ($contribution['phase'] ?? 'late')));
|
||||
self::assertContains(
|
||||
$phase,
|
||||
['early', 'default', 'late'],
|
||||
"Module '{$module['id']}' runtime.component[{$index}] has invalid phase '{$phase}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Routes ──────────────────────────────────────────────────────
|
||||
|
||||
public function testRoutesHavePathAndTarget(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
foreach ($module['manifest']->routes as $idx => $route) {
|
||||
self::assertArrayHasKey(
|
||||
'path',
|
||||
$route,
|
||||
"Module '{$module['id']}' route[{$idx}] is missing 'path'"
|
||||
);
|
||||
self::assertArrayHasKey(
|
||||
'target',
|
||||
$route,
|
||||
"Module '{$module['id']}' route[{$idx}] is missing 'target'"
|
||||
);
|
||||
self::assertNotEmpty(
|
||||
trim((string) $route['path']),
|
||||
"Module '{$module['id']}' route[{$idx}] has empty 'path'"
|
||||
);
|
||||
self::assertNotEmpty(
|
||||
trim((string) $route['target']),
|
||||
"Module '{$module['id']}' route[{$idx}] has empty 'target'"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Pages directory ─────────────────────────────────────────────
|
||||
|
||||
public function testModulesWithRoutesHavePagesDirectory(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
if (empty($module['manifest']->routes)) {
|
||||
continue;
|
||||
}
|
||||
self::assertDirectoryExists(
|
||||
$module['path'] . '/pages',
|
||||
"Module '{$module['id']}' declares routes but has no pages/ directory"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Namespace ownership ───────────────────────────────────────
|
||||
|
||||
/**
|
||||
* All PHP classes under modules/<id>/lib/ must use a MintyPHP\Module\<Name>\
|
||||
* namespace — never a Core namespace like MintyPHP\Service\ or MintyPHP\Repository\.
|
||||
*
|
||||
* This prevents module code from masquerading as core code and ensures
|
||||
* `grep MintyPHP\Module\` reliably finds all module-owned classes.
|
||||
*/
|
||||
public function testModuleClassesUseModuleNamespace(): void
|
||||
{
|
||||
$coreNamespacePrefixes = [
|
||||
'MintyPHP\\Service\\',
|
||||
'MintyPHP\\Repository\\',
|
||||
'MintyPHP\\Support\\',
|
||||
'MintyPHP\\Http\\',
|
||||
'MintyPHP\\App\\Container\\',
|
||||
];
|
||||
|
||||
foreach (self::$modules as $module) {
|
||||
$libDir = $module['path'] . '/lib';
|
||||
if (!is_dir($libDir)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($libDir, \FilesystemIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->getExtension() !== 'php') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$content = file_get_contents($file->getPathname());
|
||||
if ($content === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^namespace\s+(.+?);/m', $content, $match)) {
|
||||
$namespace = $match[1];
|
||||
foreach ($coreNamespacePrefixes as $corePrefix) {
|
||||
self::assertFalse(
|
||||
str_starts_with($namespace . '\\', $corePrefix),
|
||||
"Module '{$module['id']}' class in {$file->getFilename()} uses core namespace '{$namespace}'. "
|
||||
. "Module classes must use MintyPHP\\Module\\* namespace."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── No hardcoded Core ability imports in module pages ───────────
|
||||
|
||||
public function testModulePagesDoNotImportCoreAbilityConstants(): void
|
||||
{
|
||||
foreach (self::$modules as $module) {
|
||||
$pagesDir = $module['path'] . '/pages';
|
||||
if (!is_dir($pagesDir)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($pagesDir)
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if (!$file->isFile() || $file->getExtension() !== 'php') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$content = file_get_contents($file->getPathname());
|
||||
if ($content === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Module pages should use their own policy constants, not Core's OperationsAuthorizationPolicy
|
||||
self::assertStringNotContainsString(
|
||||
'OperationsAuthorizationPolicy::ABILITY_',
|
||||
$content,
|
||||
"Module '{$module['id']}' page '{$file->getFilename()}' imports Core OperationsAuthorizationPolicy ability. "
|
||||
. "Use the module's own AuthorizationPolicy instead."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
|
||||
130
tests/Service/Scheduler/ScheduledJobRegistryTest.php
Normal file
130
tests/Service/Scheduler/ScheduledJobRegistryTest.php
Normal 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],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
37
tests/Support/AppContainerIsolationTrait.php
Normal file
37
tests/Support/AppContainerIsolationTrait.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Support;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
|
||||
trait AppContainerIsolationTrait
|
||||
{
|
||||
private mixed $appContainerIsolationPrevious = null;
|
||||
private bool $appContainerIsolationActive = false;
|
||||
|
||||
protected function pushAppContainer(AppContainer $container): void
|
||||
{
|
||||
if (!$this->appContainerIsolationActive) {
|
||||
$this->appContainerIsolationPrevious = $GLOBALS['minty_app_container'] ?? null;
|
||||
$this->appContainerIsolationActive = true;
|
||||
}
|
||||
|
||||
$GLOBALS['minty_app_container'] = $container;
|
||||
}
|
||||
|
||||
protected function restoreAppContainer(): void
|
||||
{
|
||||
if (!$this->appContainerIsolationActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->appContainerIsolationPrevious instanceof AppContainer) {
|
||||
$GLOBALS['minty_app_container'] = $this->appContainerIsolationPrevious;
|
||||
} else {
|
||||
unset($GLOBALS['minty_app_container']);
|
||||
}
|
||||
|
||||
$this->appContainerIsolationPrevious = null;
|
||||
$this->appContainerIsolationActive = false;
|
||||
}
|
||||
}
|
||||
70
tests/Support/AppContainerIsolationTraitTest.php
Normal file
70
tests/Support/AppContainerIsolationTraitTest.php
Normal file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Support;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class AppContainerIsolationTraitTest extends TestCase
|
||||
{
|
||||
public function testPushAndRestoreRoundTripKeepsOriginalGlobalContainer(): void
|
||||
{
|
||||
$original = $GLOBALS['minty_app_container'] ?? null;
|
||||
self::assertInstanceOf(AppContainer::class, $original);
|
||||
|
||||
$harness = new class () {
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
public function push(AppContainer $container): void
|
||||
{
|
||||
$this->pushAppContainer($container);
|
||||
}
|
||||
|
||||
public function restore(): void
|
||||
{
|
||||
$this->restoreAppContainer();
|
||||
}
|
||||
};
|
||||
|
||||
$replacement = new AppContainer();
|
||||
$harness->push($replacement);
|
||||
|
||||
self::assertSame($replacement, $GLOBALS['minty_app_container'] ?? null);
|
||||
|
||||
$harness->restore();
|
||||
|
||||
self::assertSame($original, $GLOBALS['minty_app_container'] ?? null);
|
||||
}
|
||||
|
||||
public function testMultiplePushesRestoreToInitialContainer(): void
|
||||
{
|
||||
$original = $GLOBALS['minty_app_container'] ?? null;
|
||||
self::assertInstanceOf(AppContainer::class, $original);
|
||||
|
||||
$harness = new class () {
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
public function push(AppContainer $container): void
|
||||
{
|
||||
$this->pushAppContainer($container);
|
||||
}
|
||||
|
||||
public function restore(): void
|
||||
{
|
||||
$this->restoreAppContainer();
|
||||
}
|
||||
};
|
||||
|
||||
$first = new AppContainer();
|
||||
$second = new AppContainer();
|
||||
|
||||
$harness->push($first);
|
||||
$harness->push($second);
|
||||
|
||||
self::assertSame($second, $GLOBALS['minty_app_container'] ?? null);
|
||||
|
||||
$harness->restore();
|
||||
|
||||
self::assertSame($original, $GLOBALS['minty_app_container'] ?? null);
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,13 @@ namespace MintyPHP\Tests\Support;
|
||||
use MintyPHP\App\AppContainer;
|
||||
use MintyPHP\Service\Settings\SettingCacheService;
|
||||
use MintyPHP\Service\Settings\ThemeConfigGateway;
|
||||
use MintyPHP\Tests\Support\AppContainerIsolationTrait;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ThemeResolutionTest extends TestCase
|
||||
{
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
private AppContainer $container;
|
||||
|
||||
protected function setUp(): void
|
||||
@@ -23,11 +26,12 @@ class ThemeResolutionTest extends TestCase
|
||||
|
||||
$this->setAppSettings([]);
|
||||
|
||||
$GLOBALS['minty_app_container'] = $this->container;
|
||||
$this->pushAppContainer($this->container);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->restoreAppContainer();
|
||||
$_SESSION = [];
|
||||
}
|
||||
|
||||
|
||||
@@ -4,24 +4,34 @@ namespace MintyPHP\Tests\Unit\Module;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
use MintyPHP\Module\AddressBook\Providers\AddressBookLayoutProvider;
|
||||
use MintyPHP\Tests\Support\AppContainerIsolationTrait;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Verifies that the AddressBookLayoutProvider correctly contributes
|
||||
* the 'addressBook' key to the layout context.
|
||||
* the 'addressbook.nav' key to the layout context.
|
||||
*/
|
||||
final class LayoutContextProviderTest extends TestCase
|
||||
{
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
// Guard against other tests overwriting the global container
|
||||
if (!($GLOBALS['minty_app_container'] ?? null) instanceof AppContainer
|
||||
|| !($GLOBALS['minty_app_container'])->has(\MintyPHP\App\Module\ModuleRegistry::class)) {
|
||||
|| !($GLOBALS['minty_app_container'])->has(\MintyPHP\App\Module\ModuleRegistry::class)
|
||||
|| !($GLOBALS['minty_app_container'])->has(\MintyPHP\Service\Access\UiAccessService::class)) {
|
||||
$container = require dirname(__DIR__, 3) . '/lib/App/registerContainer.php';
|
||||
$this->pushAppContainer($container);
|
||||
setAppContainer($container);
|
||||
}
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->restoreAppContainer();
|
||||
}
|
||||
|
||||
public function testProviderReturnsAddressBookKey(): void
|
||||
{
|
||||
$provider = new AddressBookLayoutProvider();
|
||||
@@ -38,8 +48,8 @@ final class LayoutContextProviderTest extends TestCase
|
||||
|
||||
$result = $provider->provide($session, $container);
|
||||
|
||||
self::assertArrayHasKey('addressBook', $result);
|
||||
$ab = $result['addressBook'];
|
||||
self::assertArrayHasKey('addressbook.nav', $result);
|
||||
$ab = $result['addressbook.nav'];
|
||||
self::assertArrayHasKey('url', $ab);
|
||||
self::assertArrayHasKey('activeSearch', $ab);
|
||||
self::assertArrayHasKey('activeTenants', $ab);
|
||||
@@ -57,18 +67,17 @@ final class LayoutContextProviderTest extends TestCase
|
||||
|
||||
$result = $provider->provide([], $container);
|
||||
|
||||
self::assertArrayHasKey('addressBook', $result);
|
||||
self::assertSame([], $result['addressBook']['peopleGroups']);
|
||||
self::assertArrayHasKey('addressbook.nav', $result);
|
||||
self::assertSame([], $result['addressbook.nav']['peopleGroups']);
|
||||
}
|
||||
|
||||
public function testProviderIsIncludedInLayoutNavWhenModuleActive(): void
|
||||
{
|
||||
// When the module is active, appBuildLayoutNavContext() should include
|
||||
// addressBook via the provider loop
|
||||
$layoutAuth = app(\MintyPHP\Service\Access\UiAccessService::class)->layoutCapabilities(0);
|
||||
$layoutNav = appBuildLayoutNavContext($layoutAuth, [], []);
|
||||
// addressbook.nav via the provider loop
|
||||
$layoutNav = appBuildLayoutNavContext([], [], []);
|
||||
|
||||
self::assertArrayHasKey('addressBook', $layoutNav,
|
||||
'addressBook key must be present in layoutNav when module is active');
|
||||
self::assertArrayHasKey('addressbook.nav', $layoutNav,
|
||||
'addressbook.nav key must be present in layoutNav when module is active');
|
||||
}
|
||||
}
|
||||
|
||||
110
tests/Unit/Module/LayoutNavProviderGuardTest.php
Normal file
110
tests/Unit/Module/LayoutNavProviderGuardTest.php
Normal file
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Unit\Module;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
use MintyPHP\App\Module\Contracts\LayoutContextProvider;
|
||||
use MintyPHP\App\Module\ModuleRegistry;
|
||||
use MintyPHP\Tests\Support\AppContainerIsolationTrait;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class LayoutNavProviderGuardTest extends TestCase
|
||||
{
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
private string $fixturesDir = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->fixturesDir = sys_get_temp_dir() . '/layout-provider-guard-' . uniqid();
|
||||
mkdir($this->fixturesDir, 0777, true);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->removeDir($this->fixturesDir);
|
||||
$this->restoreAppContainer();
|
||||
}
|
||||
|
||||
public function testReservedLayoutKeyIsRejected(): void
|
||||
{
|
||||
$registry = $this->createRegistryWithProvider(DummyReservedLayoutProvider::class);
|
||||
$container = new AppContainer();
|
||||
$container->set(ModuleRegistry::class, static fn (): ModuleRegistry => $registry);
|
||||
$this->pushAppContainer($container);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage("must not override reserved layout key 'moduleSlots'");
|
||||
|
||||
appBuildLayoutNavContext([], [], []);
|
||||
}
|
||||
|
||||
public function testNamespacedLayoutProviderKeyIsAccepted(): void
|
||||
{
|
||||
$registry = $this->createRegistryWithProvider(DummyNamespacedLayoutProvider::class);
|
||||
$container = new AppContainer();
|
||||
$container->set(ModuleRegistry::class, static fn (): ModuleRegistry => $registry);
|
||||
$this->pushAppContainer($container);
|
||||
|
||||
$layoutNav = appBuildLayoutNavContext([], [], []);
|
||||
|
||||
self::assertSame('ok', $layoutNav['dummy.value'] ?? null);
|
||||
}
|
||||
|
||||
private function createRegistryWithProvider(string $providerClass): ModuleRegistry
|
||||
{
|
||||
$moduleDir = $this->fixturesDir . '/dummy-module';
|
||||
mkdir($moduleDir, 0777, true);
|
||||
file_put_contents(
|
||||
$moduleDir . '/module.php',
|
||||
'<?php return ' . var_export([
|
||||
'id' => 'dummy-module',
|
||||
'layout_context_providers' => [$providerClass],
|
||||
], true) . ';'
|
||||
);
|
||||
|
||||
return ModuleRegistry::boot($this->fixturesDir, ['dummy-module']);
|
||||
}
|
||||
|
||||
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 DummyReservedLayoutProvider implements LayoutContextProvider
|
||||
{
|
||||
public function provide(array $session, AppContainer $container): array
|
||||
{
|
||||
return [
|
||||
'moduleSlots' => ['bad' => true],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
final class DummyNamespacedLayoutProvider implements LayoutContextProvider
|
||||
{
|
||||
public function provide(array $session, AppContainer $container): array
|
||||
{
|
||||
return [
|
||||
'dummy.value' => 'ok',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace MintyPHP\Tests\Unit\Module;
|
||||
use MintyPHP\App\Module\ModuleRegistry;
|
||||
use MintyPHP\Module\AddressBook\Providers\AddressBookSearchProvider;
|
||||
use MintyPHP\Support\SearchConfig;
|
||||
use MintyPHP\Tests\Support\AppContainerIsolationTrait;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
@@ -12,18 +13,15 @@ use PHPUnit\Framework\TestCase;
|
||||
*/
|
||||
final class SearchProviderCollectionTest extends TestCase
|
||||
{
|
||||
private static ?\MintyPHP\App\AppContainer $originalContainer = null;
|
||||
use AppContainerIsolationTrait;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
// Guard against other tests overwriting the global container (e.g. ThemeResolutionTest)
|
||||
if (self::$originalContainer === null) {
|
||||
self::$originalContainer = $GLOBALS['minty_app_container'] ?? null;
|
||||
}
|
||||
if (!($GLOBALS['minty_app_container'] ?? null) instanceof \MintyPHP\App\AppContainer
|
||||
|| !($GLOBALS['minty_app_container'])->has(ModuleRegistry::class)) {
|
||||
// Restore the bootstrap container that has the module registry
|
||||
$container = require dirname(__DIR__, 3) . '/lib/App/registerContainer.php';
|
||||
$this->pushAppContainer($container);
|
||||
setAppContainer($container);
|
||||
}
|
||||
SearchConfig::resetModuleProviders();
|
||||
@@ -31,6 +29,7 @@ final class SearchProviderCollectionTest extends TestCase
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->restoreAppContainer();
|
||||
SearchConfig::resetModuleProviders();
|
||||
}
|
||||
|
||||
|
||||
95
tests/Unit/Module/SessionProviderTest.php
Normal file
95
tests/Unit/Module/SessionProviderTest.php
Normal file
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Tests\Unit\Module;
|
||||
|
||||
use MintyPHP\App\AppContainer;
|
||||
use MintyPHP\App\Module\Contracts\SessionProvider;
|
||||
use MintyPHP\Module\AddressBook\Providers\AddressBookSessionProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* @covers \MintyPHP\Module\AddressBook\Providers\AddressBookSessionProvider
|
||||
*/
|
||||
final class SessionProviderTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a real AppContainer that returns null for any get() call.
|
||||
* AppContainer is final and cannot be mocked.
|
||||
*/
|
||||
private function emptyContainer(): AppContainer
|
||||
{
|
||||
return new AppContainer();
|
||||
}
|
||||
|
||||
public function testImplementsSessionProviderContract(): void
|
||||
{
|
||||
$provider = new AddressBookSessionProvider();
|
||||
self::assertInstanceOf(SessionProvider::class, $provider);
|
||||
}
|
||||
|
||||
public function testPopulateWithInvalidUserClearsSessionKey(): void
|
||||
{
|
||||
$_SESSION['available_departments_by_tenant'] = [['tenant' => 'old']];
|
||||
|
||||
$provider = new AddressBookSessionProvider();
|
||||
$provider->populate(['id' => 0], $this->emptyContainer());
|
||||
|
||||
self::assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
|
||||
}
|
||||
|
||||
public function testPopulateWithMissingUserIdClearsSessionKey(): void
|
||||
{
|
||||
$_SESSION['available_departments_by_tenant'] = [['tenant' => 'old']];
|
||||
|
||||
$provider = new AddressBookSessionProvider();
|
||||
$provider->populate([], $this->emptyContainer());
|
||||
|
||||
self::assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
|
||||
}
|
||||
|
||||
public function testPopulateReturnsEarlyWhenContainerMissesDependencies(): void
|
||||
{
|
||||
$provider = new AddressBookSessionProvider();
|
||||
// Container has no bindings → get() will throw, but provider guards with instanceof check
|
||||
// The provider should handle this gracefully (no session key set)
|
||||
try {
|
||||
$provider->populate(['id' => 42], $this->emptyContainer());
|
||||
} catch (\Throwable) {
|
||||
// Provider may throw if container has no binding — that's acceptable;
|
||||
// in production, bindings are always registered before providers run.
|
||||
}
|
||||
|
||||
self::assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
|
||||
}
|
||||
|
||||
public function testClearRemovesSessionKey(): void
|
||||
{
|
||||
$_SESSION['available_departments_by_tenant'] = [
|
||||
['tenant' => ['uuid' => 'abc'], 'departments' => []],
|
||||
];
|
||||
|
||||
$provider = new AddressBookSessionProvider();
|
||||
$provider->clear();
|
||||
|
||||
self::assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
|
||||
}
|
||||
|
||||
public function testClearIsIdempotent(): void
|
||||
{
|
||||
// Key doesn't exist — clear() should not throw
|
||||
$provider = new AddressBookSessionProvider();
|
||||
$provider->clear();
|
||||
|
||||
self::assertArrayNotHasKey('available_departments_by_tenant', $_SESSION);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user