-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDependencyInjectionBuilder.php
More file actions
56 lines (45 loc) · 1.66 KB
/
Copy pathDependencyInjectionBuilder.php
File metadata and controls
56 lines (45 loc) · 1.66 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
56
<?php
class DependencyInjectionBuilder
{
protected $_container;
public function __construct(ArrayAccess $container = null)
{
$this->_container = $container ? $container : [];
}
public function create($class, $input = [])
{
if (!isset($this->_container[$class])) {
$this->_container[$class] = $this->_getInstance($class, $input);
}
return $this->_container[$class];
}
public function call($controller, $input = [])
{
return call_user_func_array($controller, $this->_getDependencies($controller, $input));
}
protected function _getInstance($class, $input)
{
$metaClass = new ReflectionClass($class);
return $metaClass->hasMethod('__construct') ?
$metaClass->newInstanceArgs($this->_getDependencies([$class, '__construct'], $input)) :
new $class();
}
protected function _getDependencies($controller, $input)
{
$method = new ReflectionMethod($controller[0], $controller[1]);
$dependencies = [];
foreach ($method->getParameters() as $param) {
$parameterName = $param->getName();
if (isset($input[$parameterName])) {
$dependencies[$parameterName] = $input[$parameterName];
} else {
if (isset($param->getClass()->name)) {
$dependencies[$parameterName] = $this->create($param->getClass()->name);
} elseif (isset($this->_container[$parameterName])) {
$dependencies[$parameterName] = $this->_container[$parameterName];
}
}
}
return $dependencies;
}
}