diff --git a/composer.json b/composer.json index f5b92db..afcd119 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,8 @@ }, "autoload": { "psr-4": { - "InterNACHI\\Modular\\": "src/" + "InterNACHI\\Modular\\": "src/", + "InterNACHI\\Modular\\Tests\\Concerns\\": "tests/Concerns/" } }, "autoload-dev": { diff --git a/tests/Concerns/PreloadsAppModules.php b/tests/Concerns/PreloadsAppModules.php index a04f453..86756e4 100644 --- a/tests/Concerns/PreloadsAppModules.php +++ b/tests/Concerns/PreloadsAppModules.php @@ -7,12 +7,12 @@ trait PreloadsAppModules { - protected static $autoloader_registered = false; + protected static bool $autoloader_registered = false; #[Before] public function prepareTestModule(): void { - $src = __DIR__.'/../testbench-core/app-modules'; + $src = $this->appModulesFixturePath(); $dest = static::applicationBasePath().'/app-modules'; $fs = new Filesystem(); @@ -23,22 +23,39 @@ public function prepareTestModule(): void #[Before] public function prepareModuleAutoloader(): void { - if (! static::$autoloader_registered) { - spl_autoload_register(function($fqcn) { - if (str_starts_with($fqcn, 'Modules\\TestModule\\')) { - $path = str_replace( - ['Modules\\TestModule\\', '\\'], - ['', DIRECTORY_SEPARATOR], - $fqcn - ); - $path = static::applicationBasePath().'/app-modules/test-module/src/'.$path.'.php'; - if (file_exists($path)) { - include_once $path; - } - } - }); + if (static::$autoloader_registered) { + return; } + $namespaces = $this->moduleNamespaceMap(); + $base_path = static::applicationBasePath(); + + spl_autoload_register(function($fqcn) use ($namespaces, $base_path) { + foreach ($namespaces as $namespace => $module) { + if (! str_starts_with($fqcn, $namespace)) { + continue; + } + + $relative = str_replace([$namespace, '\\'], ['', DIRECTORY_SEPARATOR], $fqcn); + $path = "{$base_path}/app-modules/{$module}/src/{$relative}.php"; + + if (file_exists($path)) { + include_once $path; + return; + } + } + }); + static::$autoloader_registered = true; } + + protected function appModulesFixturePath(): string + { + return __DIR__.'/../testbench-core/app-modules'; + } + + protected function moduleNamespaceMap(): array + { + return ['Modules\\TestModule\\' => 'test-module']; + } }