pohja/Loader.php

64 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2024-02-03 14:08:03 +01:00
<?php
class Loader {
protected static array $dirs = [
"LIB_MIGRATIONS_DIR",
"LIB_TASKS_DIR",
"LIB_TEMPLATE_DIR",
"LIB_LIB_DIR",
"TASKS_DIR",
"TEMPLATE_DIR",
"LIB_DIR"
];
protected static $classmap = [];
public static function _autoload($class) {
if (count(self::$classmap) === 0) {
self::buildRecursiveClassMap();
}
if (isset(self::$classmap[$class])) {
require_once(self::$classmap[$class]);
return;
}
}
protected static function buildRecursiveClassMap() {
foreach (self::$dirs as $dir) {
if (!defined($dir)) {
continue;
}
$dir = constant($dir);
if (!is_dir($dir) || !is_readable($dir)) {
continue;
}
self::buildClassMap($dir);
}
}
protected static function buildClassMap($dir) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file === "." || $file === "..") {
continue;
}
if (is_dir($file)) {
self::buildClassMap($file);
} else {
$parts = explode(".", $file);
$ext = array_pop($parts);
if ($ext === "php") {
$classname = array_shift($parts);
self::$classmap[$classname] = $dir . "/" . $file;
}
}
}
}
}
spl_autoload_register("Loader::_autoload");