-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathAutoloader.php
86 lines (69 loc) · 2.52 KB
/
Autoloader.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
declare(strict_types=1);
namespace Doctrine\ORM\Proxy;
use Closure;
use function file_exists;
use function ltrim;
use function spl_autoload_register;
use function str_replace;
use function str_starts_with;
use function strlen;
use function substr;
use const DIRECTORY_SEPARATOR;
/**
* Special Autoloader for Proxy classes, which are not PSR-0 compliant.
*/
final class Autoloader
{
/**
* Resolves proxy class name to a filename based on the following pattern.
*
* 1. Remove Proxy namespace from class name.
* 2. Remove namespace separators from remaining class name.
* 3. Return PHP filename from proxy-dir with the result from 2.
*
* @phpstan-param class-string $className
*
* @throws NotAProxyClass
*/
public static function resolveFile(string $proxyDir, string $proxyNamespace, string $className): string
{
if (! str_starts_with($className, $proxyNamespace)) {
throw new NotAProxyClass($className, $proxyNamespace);
}
// remove proxy namespace from class name
$classNameRelativeToProxyNamespace = substr($className, strlen($proxyNamespace));
// remove namespace separators from remaining class name
$fileName = str_replace('\\', '', $classNameRelativeToProxyNamespace);
return $proxyDir . DIRECTORY_SEPARATOR . $fileName . '.php';
}
/**
* Registers and returns autoloader callback for the given proxy dir and namespace.
*
* @param Closure(string, string, class-string): void|null $notFoundCallback Invoked when the proxy file is not found.
*
* @return Closure(string): void
*/
public static function register(
string $proxyDir,
string $proxyNamespace,
Closure|null $notFoundCallback = null,
): Closure {
$proxyNamespace = ltrim($proxyNamespace, '\\');
$autoloader = /** @param class-string $className */ static function (string $className) use ($proxyDir, $proxyNamespace, $notFoundCallback): void {
if ($proxyNamespace === '') {
return;
}
if (! str_starts_with($className, $proxyNamespace)) {
return;
}
$file = Autoloader::resolveFile($proxyDir, $proxyNamespace, $className);
if ($notFoundCallback && ! file_exists($file)) {
$notFoundCallback($proxyDir, $proxyNamespace, $className);
}
require $file;
};
spl_autoload_register($autoloader);
return $autoloader;
}
}