-
Notifications
You must be signed in to change notification settings - Fork 25
/
PackageLoader.php
74 lines (66 loc) · 2.28 KB
/
PackageLoader.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
<?php
namespace PackageLoader;
class PackageLoader
{
public $dir;
public function getComposerFile()
{
return json_decode(file_get_contents($this->dir."/composer.json"), 1);
}
public function load($dir)
{
$this->dir = $dir;
$composer = $this->getComposerFile();
if(isset($composer["autoload"]["psr-4"])){
$this->loadPSR4($composer['autoload']['psr-4']);
}
if(isset($composer["autoload"]["psr-0"])){
$this->loadPSR0($composer['autoload']['psr-0']);
}
if(isset($composer["autoload"]["files"])){
$this->loadFiles($composer["autoload"]["files"]);
}
}
public function loadFiles($files){
foreach($files as $file){
$fullpath = $this->dir."/".$file;
if(file_exists($fullpath)){
include_once($fullpath);
}
}
}
public function loadPSR4($namespaces)
{
$this->loadPSR($namespaces, true);
}
public function loadPSR0($namespaces)
{
$this->loadPSR($namespaces, false);
}
public function loadPSR($namespaces, $psr4)
{
$dir = $this->dir;
// Foreach namespace specified in the composer, load the given classes
foreach ($namespaces as $namespace => $classpaths) {
if (!is_array($classpaths)) {
$classpaths = array($classpaths);
}
spl_autoload_register(function ($classname) use ($namespace, $classpaths, $dir, $psr4) {
// Check if the namespace matches the class we are looking for
if (preg_match("#^".preg_quote($namespace)."#", $classname)) {
// Remove the namespace from the file path since it's psr4
if ($psr4) {
$classname = str_replace($namespace, "", $classname);
}
$filename = preg_replace("#\\\\#", "/", $classname).".php";
foreach ($classpaths as $classpath) {
$fullpath = $dir."/".$classpath."/$filename";
if (file_exists($fullpath)) {
include_once $fullpath;
}
}
}
});
}
}
}