1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @description Dice - A minimal Dependency Injection Container for PHP |
5
|
|
|
* |
6
|
|
|
* @author Tom Butler [email protected] |
7
|
|
|
* @author Garrett Whitehorn http://garrettw.net/ |
8
|
|
|
* @copyright 2012-2018 Tom Butler <[email protected]> | https://r.je/dice.html |
9
|
|
|
* @license http://www.opensource.org/licenses/bsd-license.php BSD License |
10
|
|
|
* |
11
|
|
|
* @version 3.0 |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Dice; |
15
|
|
|
|
16
|
|
|
class Dice |
17
|
|
|
{ |
18
|
|
|
const CONSTANT = 'Dice::CONSTANT'; |
19
|
|
|
const INSTANCE = 'Dice::INSTANCE'; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var array $rules Rules which have been set using addRule() |
23
|
|
|
*/ |
24
|
|
|
private $rules = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var array $cache A cache of closures based on class name so each class is only reflected once |
28
|
|
|
*/ |
29
|
|
|
private $cache = []; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var array $instances Stores any instances marked as 'shared' so create() can return the same instance |
33
|
|
|
*/ |
34
|
|
|
private $instances = []; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Constructor which allows setting a default ruleset to apply to all objects. |
38
|
|
|
*/ |
39
|
|
|
public function __construct($defaultRule = []) |
40
|
|
|
{ |
41
|
|
|
if (!empty($defaultRule)) { |
42
|
|
|
$this->rules['*'] = $defaultRule; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Adds a rule $rule to the class $classname. |
48
|
|
|
* |
49
|
|
|
* The container can be fully configured using rules provided by associative arrays. |
50
|
|
|
* See {@link https://r.je/dice.html#example3} for a description of the rules. |
51
|
|
|
* |
52
|
|
|
* @param string $classname The name of the class to add the rule for |
53
|
|
|
* @param array $rule The rule to add to it |
54
|
|
|
*/ |
55
|
|
|
public function addRule($classname, $rule) |
56
|
|
|
{ |
57
|
|
|
if (isset($rule['instanceOf']) |
58
|
|
|
&& \is_string($rule['instanceOf']) |
59
|
|
|
&& (!\array_key_exists('inherit', $rule) || $rule['inherit'] === true) |
60
|
|
|
) { |
61
|
|
|
$rule = \array_replace_recursive($this->getRule($rule['instanceOf']), $rule); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// Allow substitutions rules to be defined with a leading a slash |
65
|
|
|
if (isset($rule['substitutions'])) { |
66
|
|
|
foreach ($rule['substitutions'] as $key => $value) { |
67
|
|
|
$rule['substitutions'][self::normalizeNamespace($key)] = $value; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
$this->rules[self::normalizeName($classname)] = \array_replace_recursive($this->getRule($classname), $rule); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Add rules as array. Useful for JSON loading |
75
|
|
|
* $dice->addRules(json_decode(file_get_contents('foo.json')); |
76
|
|
|
* |
77
|
|
|
* @param array $rules Rules in a single array [name => $rule] format |
78
|
|
|
*/ |
79
|
|
|
public function addRules(array $rules) |
80
|
|
|
{ |
81
|
|
|
foreach ($rules as $name => $rule) { |
82
|
|
|
$this->addRule($name, $rule); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Returns the rule that will be applied to the class $matching during create(). |
88
|
|
|
* |
89
|
|
|
* @param string $name The name of the ruleset to get - can be a class or not |
90
|
|
|
* @return array Ruleset that applies when instantiating the given name |
91
|
|
|
*/ |
92
|
|
|
public function getRule($name) |
93
|
|
|
{ |
94
|
|
|
// first, check for exact match |
95
|
|
|
$normalname = self::normalizeName($name); |
96
|
|
|
|
97
|
|
|
if (isset($this->rules[$normalname])) { |
98
|
|
|
return $this->rules[$normalname]; |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
// next, look for a rule where: |
102
|
|
|
foreach ($this->rules as $key => $rule) { |
103
|
|
|
if ($key !== '*' // it's not the default rule, |
104
|
|
|
&& \is_subclass_of($name, $key) // its name is a parent class of what we're looking for, |
105
|
|
|
&& empty($rule['instanceOf']) // it's not a named instance, |
106
|
|
|
&& (!array_key_exists('inherit', $rule) || $rule['inherit'] === true) // and it applies to subclasses |
107
|
|
|
) { |
108
|
|
|
return $rule; |
109
|
|
|
} |
110
|
|
|
} |
111
|
|
|
|
112
|
|
|
// if we get here, return the default rule if it's set |
113
|
|
|
return (isset($this->rules['*'])) ? $this->rules['*'] : []; |
114
|
|
|
} |
115
|
|
|
|
116
|
|
|
/** |
117
|
|
|
* Returns a fully constructed object based on $classname using $args and $share as constructor arguments |
118
|
|
|
* |
119
|
|
|
* @param string $classname The name of the class to instantiate |
120
|
|
|
* @param array $args An array with any additional arguments to be passed into the constructor |
121
|
|
|
* @param array $share Whether the same class instance should be passed around each time |
122
|
|
|
* @return object A fully constructed object based on the specified input arguments |
123
|
|
|
*/ |
124
|
|
|
public function create($classname, array $args = [], array $share = []) |
125
|
|
|
{ |
126
|
|
|
if (!empty($this->instances[$classname])) { |
127
|
|
|
// we've already created a shared instance so return it to save the closure call. |
128
|
|
|
return $this->instances[$classname]; |
129
|
|
|
} |
130
|
|
|
|
131
|
|
|
// so now, we either need a new instance or just don't have one stored |
132
|
|
|
// but if we have the closure stored that creates it, call that |
133
|
|
|
if (!empty($this->cache[$classname])) { |
134
|
|
|
return $this->cache[$classname]($args, $share); |
135
|
|
|
} |
136
|
|
|
|
137
|
|
|
$rule = $this->getRule($classname); |
138
|
|
|
// Reflect the class for inspection, this should only ever be done once per class and then be cached |
139
|
|
|
$class = new \ReflectionClass(isset($rule['instanceOf']) ? $rule['instanceOf'] : $classname); |
140
|
|
|
$constructor = $class->getConstructor(); |
141
|
|
|
// Create parameter-generating closure in order to cache reflection on the parameters. |
142
|
|
|
// This way $reflectmethod->getParameters() only ever gets called once. |
143
|
|
|
$params = (isset($constructor)) ? $this->getParams($constructor, $rule) : null; |
144
|
|
|
|
145
|
|
|
$closure = $this->getClosure($class, $params); |
146
|
|
|
|
147
|
|
|
// Get a closure based on the type of object being created: shared, normal, or constructorless |
148
|
|
|
if (isset($rule['shared']) && $rule['shared'] === true) { |
149
|
|
|
$closure = function(array $args, array $share) use ($classname, $class, $constructor, $params, $closure) { |
150
|
|
|
if ($class->isInternal() === true) { |
151
|
|
|
$this->instances[$classname] = $closure($args, $share); |
152
|
|
|
} else if (isset($constructor)) { |
153
|
|
|
try { |
154
|
|
|
// Shared instance: create without calling constructor (and write to \$classname and $classname, see issue #68) |
155
|
|
|
$this->instances[$classname] = $class->newInstanceWithoutConstructor(); |
156
|
|
|
// Now call constructor after constructing all dependencies. Avoids problems with cyclic references (issue #7) |
157
|
|
|
$constructor->invokeArgs($this->instances[$classname], $params($args, $share)); |
158
|
|
|
} catch (\ReflectionException $e) { |
159
|
|
|
$this->instances[$classname] = $class->newInstanceArgs($params($args, $share)); |
160
|
|
|
} |
161
|
|
|
} else { |
162
|
|
|
$this->instances[$classname] = $class->newInstanceWithoutConstructor(); |
163
|
|
|
} |
164
|
|
|
|
165
|
|
|
$this->instances[self::normalizeNamespace($classname)] = $this->instances[$classname]; |
166
|
|
|
|
167
|
|
|
return $this->instances[$classname]; |
168
|
|
|
}; |
169
|
|
|
} |
170
|
|
|
|
171
|
|
|
//If there are shared instances, create them and merge them with shared instances higher up the object graph |
172
|
|
|
if (isset($rule['shareInstances'])) { |
173
|
|
|
$closure = function(array $args, array $share) use ($closure, $rule) { |
174
|
|
|
foreach ($rule['shareInstances'] as $instance) { |
175
|
|
|
$share[] = $this->create($instance, [], $share); |
176
|
|
|
} |
177
|
|
|
return $closure($args, $share); |
178
|
|
|
}; |
179
|
|
|
} |
180
|
|
|
|
181
|
|
|
// When $rule['call'] is set, wrap the closure in another closure which calls the required methods after constructing the object. |
182
|
|
|
// By putting this in a closure, the loop is never executed unless call is actually set. |
183
|
|
|
if (isset($rule['call'])) { |
184
|
|
|
$closure = function(array $args, array $share) use ($closure, $class, $rule) { |
185
|
|
|
// Construct the object using the original closure |
186
|
|
|
$object = $closure($args, $share); |
187
|
|
|
|
188
|
|
|
foreach ($rule['call'] as $call) { |
189
|
|
|
// Generate the method arguments using getParams() and call the returned closure |
190
|
|
|
// (in php7 it will be ()() rather than __invoke) |
191
|
|
|
$shareRule = ['shareInstances' => isset($rule['shareInstances']) ? $rule['shareInstances'] : []]; |
192
|
|
|
$callMeMaybe = isset($call[1]) ? $call[1] : []; |
193
|
|
|
$return = call_user_func_array( |
194
|
|
|
[$object, $call[0]], |
195
|
|
|
$this->getParams($class->getMethod($call[0]), $shareRule) |
196
|
|
|
->__invoke($this->expand($callMeMaybe)) |
197
|
|
|
); |
198
|
|
|
|
199
|
|
|
if (isset($call[2]) && is_callable($call[2])) { |
200
|
|
|
call_user_func($call[2], $return); |
201
|
|
|
} |
202
|
|
|
} |
203
|
|
|
|
204
|
|
|
return $object; |
205
|
|
|
}; |
206
|
|
|
} |
207
|
|
|
|
208
|
|
|
$this->cache[$classname] = $closure; |
209
|
|
|
|
210
|
|
|
return $this->cache[$classname]($args, $share); |
211
|
|
|
} |
212
|
|
|
|
213
|
|
|
/** |
214
|
|
|
* Returns a closure for creating object, caching the reflection object for later use. |
215
|
|
|
* |
216
|
|
|
* The container can be fully configured using rules provided by associative arrays. |
217
|
|
|
* See {@link https://r.je/dice.html#example3} for a description of the rules. |
218
|
|
|
* |
219
|
|
|
* @param \ReflectionClass $class The reflection object used to inspect the class |
220
|
|
|
* @param \Closure|null $params The output of getParams() |
221
|
|
|
* @return \Closure A closure that will create the appropriate object when called |
222
|
|
|
*/ |
223
|
|
|
private function getClosure(\ReflectionClass $class, $params) |
224
|
|
|
{ |
225
|
|
|
// PHP throws a fatal error rather than an exception when trying to |
226
|
|
|
// instantiate an interface - detect it and throw an exception instead |
227
|
|
|
if ($class->isInterface()) { |
228
|
|
|
return function() { |
229
|
|
|
throw new \InvalidArgumentException('Cannot instantiate interface'); |
230
|
|
|
}; |
231
|
|
|
} |
232
|
|
|
|
233
|
|
|
if ($params) { |
234
|
|
|
// This class has dependencies, call the $params closure to generate them based on $args and $share |
235
|
|
|
return function(array $args, array $share) use ($class, $params) { |
236
|
|
|
return $class->newInstanceArgs($params($args, $share)); |
237
|
|
|
}; |
238
|
|
|
} |
239
|
|
|
|
240
|
|
|
return function() use ($class) { |
241
|
|
|
// No constructor arguments, just instantiate the class |
242
|
|
|
return new $class->name(); |
243
|
|
|
}; |
244
|
|
|
} |
245
|
|
|
|
246
|
|
|
/** |
247
|
|
|
* Returns a closure that generates arguments for $method based on $rule and any $args passed into the closure |
248
|
|
|
* |
249
|
|
|
* @param \ReflectionMethod $method A reflection of the method to inspect |
250
|
|
|
* @param array $rule The ruleset to use in interpreting what the params should be |
251
|
|
|
* @return \Closure A closure that uses the cached information to generate the method's arguments |
252
|
|
|
*/ |
253
|
|
|
private function getParams(\ReflectionMethod $method, array $rule) |
254
|
|
|
{ |
255
|
|
|
$paramInfo = []; // Caches some information about the parameter so (slow) reflection isn't needed every time |
256
|
|
|
foreach ($method->getParameters() as $param) { |
257
|
|
|
// get the class hint of each param, if there is one |
258
|
|
|
$class = ($class = $param->getClass()) ? $class->name : null; |
259
|
|
|
// determine if the param can be null, if we need to substitute a |
260
|
|
|
// different class, or if we need to force a new instance for it |
261
|
|
|
$paramInfo[] = [ |
262
|
|
|
$class, |
263
|
|
|
$param, |
264
|
|
|
isset($rule['substitutions']) && \array_key_exists($class, $rule['substitutions']), |
265
|
|
|
]; |
266
|
|
|
} |
267
|
|
|
$php56 = \method_exists('ReflectionParameter', 'isVariadic'); // marginally faster than checking PHP_VERSION |
268
|
|
|
|
269
|
|
|
// Return a closure that uses the cached information to generate the arguments for the method |
270
|
|
|
return function(array $args, array $share = []) use ($paramInfo, $rule, $php56) { |
271
|
|
|
// Now merge all the possible parameters: user-defined in the rule via constructParams, |
272
|
|
|
// shared instances, and the $args argument from $dice->create() |
273
|
|
|
if (!empty($share) || isset($rule['constructParams'])) { |
274
|
|
|
$args = \array_merge( |
275
|
|
|
$args, |
276
|
|
|
(isset($rule['constructParams'])) ? $this->expand($rule['constructParams'], $share) : [], |
277
|
|
|
$share |
278
|
|
|
); |
279
|
|
|
} |
280
|
|
|
|
281
|
|
|
$parameters = []; |
282
|
|
|
|
283
|
|
|
// Now find a value for each method parameter |
284
|
|
|
foreach ($paramInfo as $pi) { |
285
|
|
|
list($class, $param, $sub) = $pi; |
286
|
|
|
|
287
|
|
|
// First, loop through $args and see if each value can match the current parameter based on type hint |
288
|
|
|
// This if statement actually gives a ~10% speed increase when $args isn't set |
289
|
|
|
if (!empty($args)) { |
290
|
|
|
foreach ($args as $i => $arg) { |
291
|
|
|
if ($class !== null |
292
|
|
|
&& ($arg instanceof $class || ($arg === null && $param->allowsNull())) |
293
|
|
|
) { |
294
|
|
|
// The argument matches, store and remove from $args so it won't wrongly match another parameter |
295
|
|
|
$parameters[] = \array_splice($args, $i, 1)[0]; |
296
|
|
|
continue 2; //Move on to the next parameter |
297
|
|
|
} |
298
|
|
|
} |
299
|
|
|
} |
300
|
|
|
|
301
|
|
|
// When nothing from $args matches but a class is type hinted, create an instance to use, using a substitution if set |
302
|
|
|
if ($class !== null) { |
303
|
|
|
try { |
304
|
|
|
$parameters[] = ($sub) |
305
|
|
|
? $this->expand($rule['substitutions'][$class], $share, true) |
306
|
|
|
: $this->create($class, [], $share); |
307
|
|
|
} catch (\InvalidArgumentException $e) { |
308
|
|
|
// Squash this exception |
309
|
|
|
} |
310
|
|
|
continue; |
311
|
|
|
} |
312
|
|
|
|
313
|
|
|
// Variadic functions will only have one argument. To account for those, append any remaining arguments to the list |
314
|
|
|
if ($php56 && $param->isVariadic()) { |
315
|
|
|
$parameters = array_merge($parameters, $args); |
316
|
|
|
continue; |
317
|
|
|
} |
318
|
|
|
|
319
|
|
|
// There is no type hint, so take the next available value from $args (and remove from $args to stop it being reused) |
320
|
|
|
if (!empty($args)) { |
321
|
|
|
$parameters[] = $this->expand(\array_shift($args)); |
322
|
|
|
continue; |
323
|
|
|
} |
324
|
|
|
|
325
|
|
|
// There's no type hint and nothing left in $args, so provide the default value or null |
326
|
|
|
$parameters[] = ($param->isDefaultValueAvailable()) ? $param->getDefaultValue() : null; |
327
|
|
|
} |
328
|
|
|
|
329
|
|
|
return ($php56) ? $parameters : array_merge($parameters, $args); |
330
|
|
|
}; |
331
|
|
|
} |
332
|
|
|
|
333
|
|
|
/** |
334
|
|
|
* Looks for Dice::INSTANCE or Dice::CONSTANT array keys in $param, and when found, returns an object based on the value. |
335
|
|
|
* See {@link https:// r.je/dice.html#example3-1} |
336
|
|
|
* |
337
|
|
|
* @param string|array $param |
338
|
|
|
* @param array $share Array of instances from 'shareInstances', required for calls to `create` |
339
|
|
|
* @param bool $createFromString |
340
|
|
|
* @return mixed |
341
|
|
|
*/ |
342
|
|
|
private function expand($param, array $share = [], $createFromString = false) |
343
|
|
|
{ |
344
|
|
|
if (!\is_array($param)) { |
345
|
|
|
// doesn't need any processing |
346
|
|
|
return (is_string($param) && $createFromString) ? $this->create($param) : $param; |
347
|
|
|
} |
348
|
|
|
|
349
|
|
|
if (isset($param[self::CONSTANT])) { |
350
|
|
|
return constant($param[self::CONSTANT]); |
351
|
|
|
} |
352
|
|
|
|
353
|
|
|
if (!isset($param[self::INSTANCE])) { |
354
|
|
|
// not a lazy instance, so recursively search for any self::INSTANCE keys on deeper levels |
355
|
|
|
foreach ($param as $name => $value) { |
356
|
|
|
$param[$name] = $this->expand($value, $share); |
357
|
|
|
} |
358
|
|
|
|
359
|
|
|
return $param; |
360
|
|
|
} |
361
|
|
|
|
362
|
|
|
// Check for 'params' which allows parameters to be sent to the instance when it's created |
363
|
|
|
// Either as a callback method or to the constructor of the instance |
364
|
|
|
$args = isset($param['params']) ? $this->expand($param['params']) : []; |
365
|
|
|
|
366
|
|
|
// for [self::INSTANCE => ['className', 'methodName'] construct the instance before calling it |
367
|
|
|
if (\is_array($param[self::INSTANCE])) { |
368
|
|
|
$param[self::INSTANCE][0] = $this->expand($param[self::INSTANCE][0], $share, true); |
369
|
|
|
} |
370
|
|
|
|
371
|
|
|
if (\is_callable($param[self::INSTANCE])) { |
372
|
|
|
// it's a lazy instance formed by a function. Call or return the value stored under the key self::INSTANCE |
373
|
|
|
if (isset($param['params']) && is_array($args)) { |
374
|
|
|
return \call_user_func_array($param[self::INSTANCE], $args); |
375
|
|
|
} |
376
|
|
|
|
377
|
|
|
return \call_user_func($param[self::INSTANCE]); |
378
|
|
|
} |
379
|
|
|
|
380
|
|
|
if (\is_string($param[self::INSTANCE])) { |
381
|
|
|
// it's a lazy instance's class name string |
382
|
|
|
return $this->create($param[self::INSTANCE], (is_array($args)) ? \array_merge($args, $share) : $share); |
383
|
|
|
} |
384
|
|
|
// if it's not a string, it's malformed. *shrug* |
385
|
|
|
} |
386
|
|
|
|
387
|
|
|
/** |
388
|
|
|
* @param string $name |
389
|
|
|
*/ |
390
|
|
|
private static function normalizeName($name) |
391
|
|
|
{ |
392
|
|
|
return \strtolower(self::normalizeNamespace($name)); |
393
|
|
|
} |
394
|
|
|
|
395
|
|
|
/** |
396
|
|
|
* @param string $name |
397
|
|
|
*/ |
398
|
|
|
private static function normalizeNamespace($name) |
399
|
|
|
{ |
400
|
|
|
return \ltrim($name, '\\'); |
401
|
|
|
} |
402
|
|
|
} |
403
|
|
|
|