-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneFileClassLoader.php
More file actions
55 lines (47 loc) · 1.36 KB
/
OneFileClassLoader.php
File metadata and controls
55 lines (47 loc) · 1.36 KB
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
<?php
namespace Oro\Component\PhpUtils;
/**
* A simple and fast implementation of the class loader
* that can be used to map one namespace to one file contains all classes from this namespace.
*/
class OneFileClassLoader
{
private string $namespacePrefix;
private string $filePath;
private static array $isFileLoaded = [];
public function __construct(string $namespacePrefix, string $filePath)
{
$this->namespacePrefix = $namespacePrefix;
$this->filePath = $filePath;
}
/**
* Registers this class loader on the SPL autoload stack.
*/
public function register(): void
{
spl_autoload_register([$this, 'loadClass']);
}
/**
* Removes this class loader from the SPL autoload stack.
*/
public function unregister(): void
{
spl_autoload_unregister([$this, 'loadClass']);
}
/**
* Loads the given class.
*/
public function loadClass(string $className): bool
{
if (!str_starts_with($className, $this->namespacePrefix)) {
return false;
}
if (!isset(self::$isFileLoaded[$this->namespacePrefix])) {
self::$isFileLoaded[$this->namespacePrefix] = true;
if (false === @include $this->filePath) {
return false;
}
}
return class_exists($className, false);
}
}