57 lines
1.5 KiB
PHP
57 lines
1.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace MintyPHP\App\Module;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Runtime autoloader for module-local PHP classes.
|
||
|
|
*
|
||
|
|
* Modules can place PHP code under modules/<id>/lib and use the same
|
||
|
|
* MintyPHP namespace root as core classes.
|
||
|
|
*/
|
||
|
|
final class ModuleAutoloader
|
||
|
|
{
|
||
|
|
/** @var list<string> */
|
||
|
|
private static array $moduleLibDirs = [];
|
||
|
|
|
||
|
|
private static bool $registered = false;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param list<ModuleManifest> $manifests
|
||
|
|
*/
|
||
|
|
public static function register(array $manifests): void
|
||
|
|
{
|
||
|
|
$dirs = self::$moduleLibDirs;
|
||
|
|
foreach ($manifests as $manifest) {
|
||
|
|
$libDir = rtrim($manifest->basePath, '/') . '/lib';
|
||
|
|
if (is_dir($libDir)) {
|
||
|
|
$dirs[] = $libDir;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
self::$moduleLibDirs = array_values(array_unique($dirs));
|
||
|
|
|
||
|
|
if (self::$registered) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
spl_autoload_register([self::class, 'autoload'], true, true);
|
||
|
|
self::$registered = true;
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function autoload(string $class): void
|
||
|
|
{
|
||
|
|
$prefix = 'MintyPHP\\';
|
||
|
|
if (!str_starts_with($class, $prefix)) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
$relativePath = str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
|
||
|
|
foreach (self::$moduleLibDirs as $libDir) {
|
||
|
|
$candidate = $libDir . '/' . $relativePath;
|
||
|
|
if (is_file($candidate)) {
|
||
|
|
require_once $candidate;
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|