-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoload.php
56 lines (48 loc) · 1.47 KB
/
autoload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php namespace Obie;
// Set globals
if (defined('IN_OBIE')) {
return;
}
define('IN_OBIE', true);
if (!defined('OBIE_BASE_DIR')) {
define('OBIE_BASE_DIR', __DIR__);
}
// Register class autoloader
spl_autoload_register(function(string $name) {
static $base_path = OBIE_BASE_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
$ns_parts = explode('\\', $name);
// Only apply this autoloader to classes beginning with the namespace of this file
if (count($ns_parts) < 2 || $ns_parts[0] !== __NAMESPACE__) {
return;
}
for ($i = 1; $i < count($ns_parts); $i++) {
// Convert item to snake case
$ns_parts[$i] = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $ns_parts[$i]));
// Get current path
$cur_path = $base_path . implode(DIRECTORY_SEPARATOR, array_slice($ns_parts, 1, $i));
if ($i === count($ns_parts) - 1) {
// Attempt to load 'class_name.php'
$cur_file = realpath($cur_path . '.php');
if (
$cur_file !== false &&
strncmp($cur_file, $base_path, strlen($base_path)) === 0 &&
file_exists($cur_file) &&
is_file($cur_file)
) {
require $cur_file;
}
// Attempt to load 'class_name/index.php'
$cur_file = realpath($cur_path . DIRECTORY_SEPARATOR . 'index.php');
if (
$cur_file !== false &&
strncmp($cur_file, $base_path, strlen($base_path)) === 0 &&
file_exists($cur_file) &&
is_file($cur_file)
) {
require $cur_file;
}
} else {
if (!file_exists($cur_path) || !is_dir($cur_path)) return;
}
}
});