1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Trait ClassLoader |
4
|
|
|
* |
5
|
|
|
* @filesource ClassLoader.php |
6
|
|
|
* @created 13.11.2017 |
7
|
|
|
* @package chillerlan\Traits |
8
|
|
|
* @author Smiley <[email protected]> |
9
|
|
|
* @copyright 2017 Smiley |
10
|
|
|
* @license MIT |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace chillerlan\Traits; |
14
|
|
|
|
15
|
|
|
use Exception, ReflectionClass; |
16
|
|
|
|
17
|
|
|
trait ClassLoader{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Instances an object of $class/$type with an arbitrary number of $params |
21
|
|
|
* |
22
|
|
|
* @param string $class class FQCN |
23
|
|
|
* @param string $type class/parent/interface FQCN |
24
|
|
|
* |
25
|
|
|
* @param mixed $params [optional] the following arguments will be passed to the $class constructor |
26
|
|
|
* |
27
|
|
|
* @return mixed of type $type |
28
|
|
|
* @throws \Exception |
29
|
|
|
*/ |
30
|
|
|
public function loadClass(string $class, string $type = null, ...$params){ |
31
|
|
|
$type = $type ?? $class; |
32
|
|
|
|
33
|
|
|
try{ |
34
|
|
|
$reflectionClass = new ReflectionClass($class); |
35
|
|
|
$reflectionType = new ReflectionClass($type); |
36
|
|
|
} |
37
|
|
|
catch(Exception $e){ |
38
|
|
|
throw new TraitException('ClassLoader: '.$e->getMessage()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
|
42
|
|
|
if($reflectionType->isTrait()){ |
43
|
|
|
throw new TraitException($class.' cannot be an instance of trait '.$type); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if($reflectionClass->isAbstract()){ |
47
|
|
|
throw new TraitException('cannot instance abstract class '.$class); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if($reflectionClass->isTrait()){ |
51
|
|
|
throw new TraitException('cannot instance trait '.$class); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if($class !== $type){ |
55
|
|
|
|
56
|
|
|
if($reflectionType->isInterface() && !$reflectionClass->implementsInterface($type)){ |
57
|
|
|
throw new TraitException($class.' does not implement '.$type); |
58
|
|
|
} |
59
|
|
|
elseif(!$reflectionClass->isSubclassOf($type)) { |
60
|
|
|
throw new TraitException($class.' does not inherit '.$type); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
try{ |
66
|
|
|
$object = $reflectionClass->newInstanceArgs($params); |
67
|
|
|
|
68
|
|
|
if(!$object instanceof $type){ |
69
|
|
|
throw new TraitException('how did u even get here?'); // @codeCoverageIgnore |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $object; |
73
|
|
|
} |
74
|
|
|
// @codeCoverageIgnoreStart |
75
|
|
|
// here be dragons |
76
|
|
|
catch(Exception $e){ |
77
|
|
|
throw new TraitException('ClassLoader: '.$e->getMessage()); |
78
|
|
|
} |
79
|
|
|
// @codeCoverageIgnoreEnd |
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
} |
84
|
|
|
|