Files

73 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2015-10-08 14:08:26 -04:00
<?php
class Autoloader
{
2018-05-21 11:49:15 -04:00
public static $classes = [];
2015-10-08 14:08:26 -04:00
2018-05-21 11:49:15 -04:00
public static function autoload($class)
2015-10-08 14:08:26 -04:00
{
2018-05-21 11:49:15 -04:00
if (class_exists($class, false) || interface_exists($class, false)) {
return true;
}
$class = strtolower($class);
$path = static::$classes[$class] ?? false;
if ($path) {
require_once $path;
return true;
}
return false;
2015-10-08 14:08:26 -04:00
}
2018-05-21 11:49:15 -04:00
public static function reload($reload = false)
2015-10-08 14:08:26 -04:00
{
2018-05-21 11:49:15 -04:00
$key = 'lbry-classes-5';
if (ini_get('apc.enabled') && !$reload) {
2018-12-05 10:35:37 -05:00
$classes = apcu_fetch($key, $success);
2018-05-21 11:49:15 -04:00
if ($success) {
static::$classes = $classes;
return;
}
}
static::$classes = [];
$dir = new RecursiveDirectoryIterator(ROOT_DIR, RecursiveDirectoryIterator::SKIP_DOTS);
$ite = new RecursiveIteratorIterator($dir);
$pathIterator = new RegexIterator($ite, '/.*\.php$/', RegexIterator::GET_MATCH);
foreach ($pathIterator as $paths) {
foreach ($paths as $path) {
static::$classes += static::parseFile($path);
}
}
if (ini_get('apc.enabled')) {
2018-12-05 10:35:37 -05:00
apcu_store($key, static::$classes);
2018-05-21 11:49:15 -04:00
}
2015-10-08 14:08:26 -04:00
}
2018-05-21 11:49:15 -04:00
protected static function parseFile($path)
2015-10-08 14:08:26 -04:00
{
2018-05-21 11:49:15 -04:00
$mapping = [];
$classes = [];
preg_match_all('~^\s*(?:namespace)\s+([^;]+)~mi', file_get_contents($path), $namespaces);
preg_match_all('~^\s*(?:abstract\s+|final\s+)?(?:class|interface)\s+(\w+)~mi', file_get_contents($path), $classes);
if (isset($namespaces[1]) && count($namespaces[1]) > 2) {
throw new RuntimeException('Autoloader cannot handle 2 namespaces in the same file');
}
$prefix = isset($namespaces[1]) && count($namespaces[1]) ? reset($namespaces[1]) . '\\' : '';
foreach ($classes[1] as $class) {
$mapping[strtolower($prefix . $class)] = $path;
}
return $mapping;
2015-10-08 14:08:26 -04:00
}
}
ini_set('unserialize_callback_func', 'spl_autoload_call');
spl_autoload_register('Autoloader::autoload');
Autoloader::reload(true);