-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefinitionResolver.php
More file actions
111 lines (96 loc) · 2.76 KB
/
DefinitionResolver.php
File metadata and controls
111 lines (96 loc) · 2.76 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
namespace Rad\DependencyInjection;
use Closure;
use ReflectionClass;
use ReflectionMethod;
/**
* Definition Resolver
*
* @package Rad\DependencyInjection
*/
class DefinitionResolver
{
protected $container;
protected $defaultDefinition = [
'class' => '',
'arguments' => [],
'call' => []
];
/**
* Rad\DependencyInjection\DefinitionResolver constructor
*
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Resolver
*
* @param mixed $definition
* @param array $args
*
* @return mixed|object
* @throws Exception
*/
public function resolver($definition, array $args = [])
{
if ($definition instanceof Closure) {
$resolvedDefinition = call_user_func_array($definition, $args);
} elseif (is_object($definition)) {
$resolvedDefinition = $definition;
} elseif (is_string($definition)) {
if (class_exists($definition)) {
$reflectionObj = new ReflectionClass($definition);
$resolvedDefinition = $reflectionObj->newInstanceArgs($args);
} else {
throw new Exception(sprintf('Class "%s" does not exist.', $definition));
}
} elseif (is_array($definition)) {
$resolvedDefinition = self::fromArray($definition);
} else {
throw new Exception(sprintf('Definition type "%s" does not support.', gettype($definition)));
}
return $resolvedDefinition;
}
/**
* Load definition from array
*
* @param array $definition
*
* @return object
*/
protected function fromArray(array $definition)
{
$definition += $this->defaultDefinition;
$refClass = new ReflectionClass($definition['class']);
$instance = $refClass->newInstanceArgs(self::parseArguments($definition['arguments']));
foreach ($definition['call'] as $methodName => $args) {
$refMethod = new ReflectionMethod($instance, $methodName);
$refMethod->invokeArgs($instance, self::parseArguments($args));
}
return $instance;
}
/**
* Parse arguments
*
* @param array $args
*
* @return array
* @throws Exception\ServiceNotFoundException
*/
protected function parseArguments(array $args)
{
$output = [];
foreach ($args as $arg) {
if (is_string($arg) && strpos($arg, '@') === 0) {
$service = substr($arg, 1);
$output[] = $this->container->get($service);
continue;
}
$output[] = $arg;
}
return $output;
}
}