Completed
Pull Request — master (#18)
by Todd
01:44
created

Container::setInherit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2017 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Container;
9
10
use Interop\Container\ContainerInterface;
11
12
/**
13
 * An inversion of control container.
14
 */
15
class Container implements ContainerInterface {
16
    private $currentRule;
17
    private $currentRuleName;
18
    private $instances;
19
    private $rules;
20
    private $factories;
21
22
    /**
23
     * Construct a new instance of the {@link Container} class.
24
     */
25 76
    public function __construct() {
26 76
        $this->rules = ['*' => ['inherit' => true, 'constructorArgs' => null]];
27 76
        $this->instances = [];
28 76
        $this->factories = [];
29
30 76
        $this->rule('*');
31 76
    }
32
33
    /**
34
     * Deep clone rules.
35
     */
36
    public function __clone() {
37
        $this->rules = $this->arrayClone($this->rules);
38
        $this->rule($this->currentRuleName);
39 77
    }
40 77
41
    /**
42
     * Deep clone an array.
43
     *
44
     * @param array $array The array to clone.
45
     * @return array Returns the cloned array.
46
     * @see http://stackoverflow.com/a/17729234
47
     */
48 1
    private function arrayClone(array $array) {
49 1
        return array_map(function ($element) {
50
            return ((is_array($element))
51
                ? $this->arrayClone($element)
52
                : ((is_object($element))
53
                    ? clone $element
54
                    : $element
55
                )
56
            );
57
        }, $array);
58 76
    }
59 76
60
    /**
61 76
     * Normalize a container entry ID.
62 34
     *
63 34
     * @param string $id The ID to normalize.
64 76
     * @return string Returns a normalized ID as a string.
65 76
     */
66
    private function normalizeID($id) {
67 76
        return ltrim($id, '\\');
68
    }
69
70
    /**
71
     * Set the current rule to the default rule.
72
     *
73
     * @return $this
74
     */
75 2
    public function defaultRule() {
76 2
        return $this->rule('*');
77
    }
78
79
    /**
80
     * Set the current rule.
81
     *
82
     * @param string $id The ID of the rule.
83
     * @return $this
84
     */
85 6
    public function rule($id) {
86 6
        $id = $this->normalizeID($id);
87 6
88
        if (!isset($this->rules[$id])) {
89
            $this->rules[$id] = [];
90
        }
91
        $this->currentRuleName = $id;
92
        $this->currentRule = &$this->rules[$id];
93
94
        return $this;
95 3
    }
96 3
97
    /**
98
     * Get the class name of the current rule.
99
     *
100
     * @return string Returns a class name.
101
     */
102
    public function getClass() {
103
        return empty($this->currentRule['class']) ? '' : $this->currentRule['class'];
104
    }
105 4
106 4
    /**
107
     * Set the name of the class for the current rule.
108 4
     *
109 1
     * @param string $className A valid class name.
110 1
     * @return $this
111 3
     */
112
    public function setClass($className) {
113 4
        $this->currentRule['class'] = $className;
114
        return $this;
115
    }
116
117
    /**
118
     * Get the rule that the current rule references.
119
     *
120
     * @return string Returns a reference name or an empty string if there is no reference.
121
     */
122
    public function getAliasOf() {
123
        return empty($this->currentRule['aliasOf']) ? '' : $this->currentRule['aliasOf'];
124
    }
125
126
    /**
127
     * Set the rule that the current rule is an alias of.
128 7
     *
129 7
     * @param string $alias The name of an entry in the container to point to.
130
     * @return $this
131 7
     */
132 1
    public function setAliasOf($alias) {
133 1
        $alias = $this->normalizeID($alias);
134 6
135
        if ($alias === $this->currentRuleName) {
136 7
            trigger_error("You cannot set alias '$alias' to itself.", E_USER_NOTICE);
137
        } else {
138
            $this->currentRule['aliasOf'] = $alias;
139
        }
140
        return $this;
141
    }
142
143
    /**
144
     * Add an alias of the current rule.
145
     *
146
     * Setting an alias to the current rule means that getting an item with the alias' name will be like getting the item
147
     * with the current rule. If the current rule is shared then the same shared instance will be returned.
148 2
     *
149 2
     * If {@link Container::addAlias()} is called with an alias that is the same as the current rule then an **E_USER_NOTICE**
150
     * level error is raised and the alias is not added.
151 2
     *
152 1
     * @param string $alias The alias to set.
153 1
     * @return $this
154
     */
155 2
    public function addAlias($alias) {
156 2
        $alias = $this->normalizeID($alias);
157
158
        if ($alias === $this->currentRuleName) {
159
            trigger_error("Tried to set alias '$alias' to self.", E_USER_NOTICE);
160
        } else {
161
            $this->rules[$alias]['aliasOf'] = $this->currentRuleName;
162
        }
163
        return $this;
164
    }
165
166 6
    /**
167 6
     * Remove an alias of the current rule.
168
     *
169 6
     * If {@link Container::removeAlias()} is called with an alias that references a different rule then an **E_USER_NOTICE**
170 6
     * level error is raised, but the alias is still removed.
171 4
     *
172 4
     * @param string $alias The alias to remove.
173 6
     * @return $this
174
     */
175 6
    public function removeAlias($alias) {
176
        $alias = $this->normalizeID($alias);
177
178
        if (!empty($this->rules[$alias]['aliasOf']) && $this->rules[$alias]['aliasOf'] !== $this->currentRuleName) {
179
            trigger_error("Alias '$alias' does not point to the current rule.", E_USER_NOTICE);
180
        }
181
182
        unset($this->rules[$alias]['aliasOf']);
183 2
        return $this;
184 2
    }
185
186
    /**
187
     * Get all of the aliases of the current rule.
188
     *
189
     * This method is intended to aid in debugging and should not be used in production as it walks the entire rule array.
190
     *
191
     * @return array Returns an array of strings representing aliases.
192
     */
193 10
    public function getAliases() {
194 10
        $result = [];
195 10
196
        foreach ($this->rules as $name => $rule) {
197
            if (!empty($rule['aliasOf']) && $rule['aliasOf'] === $this->currentRuleName) {
198
                $result[] = $name;
199
            }
200
        }
201
202
        return $result;
203 2
    }
204 2
205
    /**
206
     * Get the factory callback for the current rule.
207
     *
208
     * @return callable|null Returns the rule's factory or **null** if it has none.
209
     */
210
    public function getFactory() {
211
        return isset($this->currentRule['factory']) ? $this->currentRule['factory'] : null;
212
    }
213 25
214 25
    /**
215 25
     * Set the factory that will be used to create the instance for the current rule.
216
     *
217
     * @param callable $factory This callback will be called to create the instance for the rule.
218
     * @return $this
219
     */
220
    public function setFactory(callable $factory) {
221
        $this->currentRule['factory'] = $factory;
222
        return $this;
223 2
    }
224 2
225
    /**
226
     * Whether or not the current rule is shared.
227
     *
228
     * @return bool Returns **true** if the rule is shared or **false** otherwise.
229
     */
230
    public function isShared() {
231
        return !empty($this->currentRule['shared']);
232
    }
233 3
234 3
    /**
235 3
     * Set whether or not the current rule is shared.
236
     *
237
     * @param bool $shared Whether or not the current rule is shared.
238
     * @return $this
239
     */
240
    public function setShared($shared) {
241
        $this->currentRule['shared'] = $shared;
242
        return $this;
243 2
    }
244 2
245
    /**
246
     * Whether or not the current rule will inherit to subclasses.
247
     *
248
     * @return bool Returns **true** if the current rule inherits or **false** otherwise.
249
     */
250
    public function getInherit() {
251
        return !empty($this->currentRule['inherit']);
252
    }
253 17
254 17
    /**
255 17
     * Set whether or not the current rule extends to subclasses.
256
     *
257
     * @param bool $inherit Pass **true** to have subclasses inherit this rule or **false** otherwise.
258
     * @return $this
259
     */
260
    public function setInherit($inherit) {
261
        $this->currentRule['inherit'] = $inherit;
262
        return $this;
263
    }
264
265
    /**
266
     * Get the constructor arguments for the current rule.
267
     *
268 7
     * @return array Returns the constructor arguments for the current rule.
269 7
     */
270 7
    public function getConstructorArgs() {
271
        return empty($this->currentRule['constructorArgs']) ? [] : $this->currentRule['constructorArgs'];
272
    }
273
274
    /**
275
     * Set the constructor arguments for the current rule.
276
     *
277
     * @param array $args An array of constructor arguments.
278
     * @return $this
279
     */
280 6
    public function setConstructorArgs(array $args) {
281 6
        $this->currentRule['constructorArgs'] = $args;
282
        return $this;
283 6
    }
284
285
    /**
286
     * Set a specific shared instance into the container.
287
     *
288
     * When you set an instance into the container then it will always be returned by subsequent retrievals, even if a
289
     * rule is configured that says that instances should not be shared.
290
     *
291
     * @param string $name The name of the container entry.
292
     * @param mixed $instance This instance.
293
     * @return $this
294
     */
295
    public function setInstance($name, $instance) {
296
        $this->instances[$this->normalizeID($name)] = $instance;
297 57
        return $this;
298 57
    }
299
300 57
    /**
301
     * Add a method call to a rule.
302 14
     *
303
     * @param string $method The name of the method to call.
304
     * @param array $args The arguments to pass to the method.
305 53
     * @return $this
306
     */
307 3
    public function addCall($method, array $args = []) {
308
        $this->currentRule['calls'][] = [$method, $args];
309
310 53
        return $this;
311
    }
312 2
313
    /**
314
     * Finds an entry of the container by its identifier and returns it.
315
     *
316
     * @param string $id Identifier of the entry to look for.
317 53
     * @param array $args Additional arguments to pass to the constructor.
318
     *
319
     * @throws NotFoundException No entry was found for this identifier.
320
     * @throws ContainerException Error while retrieving the entry.
321
     *
322
     * @return mixed Entry.
323
     */
324
    public function getArgs($id, array $args = []) {
325
        $id = $this->normalizeID($id);
326 53
327 53
        if (isset($this->instances[$id])) {
328
            // A shared instance just gets returned.
329 53
            return $this->instances[$id];
330 45
        }
331
332 6
        if (isset($this->factories[$id])) {
333 4
            // The factory for this object type is already there so call it to create the instance.
334
            return $this->factories[$id]($args);
335 2
        }
336 2
337
        if (!empty($this->rules[$id]['aliasOf'])) {
338
            // This rule references another rule.
339 45
            return $this->getArgs($this->rules[$id]['aliasOf'], $args);
340 45
        }
341 45
342
        // The factory or instance isn't registered so do that now.
343
        // This call also caches the instance or factory fo faster access next time.
344 45
        return $this->createInstance($id, $args);
345 45
    }
346 34
347 10
    /**
348
     * Make a rule based on an ID.
349 10
     *
350 1
     * @param string $nid A normalized ID.
351
     * @return array Returns an array representing a rule.
352
     */
353 9
    private function makeRule($nid) {
354 3
        $rule = isset($this->rules[$nid]) ? $this->rules[$nid] : [];
355 3
356
        if (class_exists($nid)) {
357 9
            for ($class = get_parent_class($nid); !empty($class); $class = get_parent_class($class)) {
358 3
                // Don't add the rule if it doesn't say to inherit.
359 3
                if (!isset($this->rules[$class]) || (isset($this->rules[$class]['inherit']) && !$this->rules[$class]['inherit'])) {
360
                    break;
361 9
                }
362 2
                $rule += $this->rules[$class];
363 2
            }
364 2
365 2
            // Add the default rule.
366 2
            if (!empty($this->rules['*']['inherit'])) {
367 9
                $rule += $this->rules['*'];
368 45
            }
369 53
370
            // Add interface calls to the rule.
371 10
            $interfaces = class_implements($nid);
372 10
            foreach ($interfaces as $interface) {
373
                if (isset($this->rules[$interface])) {
374 53
                    $interfaceRule = $this->rules[$interface];
375
376
                    if (isset($interfaceRule['inherit']) && $interfaceRule['inherit'] === false) {
377
                        continue;
378
                    }
379
380
                    if (!isset($rule['shared']) && isset($interfaceRule['shared'])) {
381
                        $rule['shared'] = $interfaceRule['shared'];
382
                    }
383
384
                    if (!isset($rule['constructorArgs']) && isset($interfaceRule['constructorArgs'])) {
385 38
                        $rule['constructorArgs'] = $interfaceRule['constructorArgs'];
386 38
                    }
387
388 38
                    if (!empty($interfaceRule['calls'])) {
389
                        $rule['calls'] = array_merge(
390 6
                            isset($rule['calls']) ? $rule['calls'] : [],
391 6
                            $interfaceRule['calls']
392
                        );
393 6
                    }
394 3
                }
395
            }
396 3
        } elseif (!empty($this->rules['*']['inherit'])) {
397 3
            // Add the default rule.
398 3
            $rule += $this->rules['*'];
399 3
        }
400
401
        return $rule;
402
    }
403 6
404 1
    /**
405 1
     * Make a function that creates objects from a rule.
406 6
     *
407
     * @param string $nid The normalized ID of the container item.
408 32
     * @param array $rule The resolved rule for the ID.
409 1
     * @return \Closure Returns a function that when called will create a new instance of the class.
410
     * @throws NotFoundException No entry was found for this identifier.
411 31
     */
412 31
    private function makeFactory($nid, array $rule) {
413
        $className = empty($rule['class']) ? $nid : $rule['class'];
414 31
415 28
        if (!empty($rule['factory'])) {
416
            // The instance is created with a user-supplied factory function.
417
            $callback = $rule['factory'];
418 28
            $function = $this->reflectCallback($callback);
419 28
420 28
            if ($function->getNumberOfParameters() > 0) {
421
                $callbackArgs = $this->makeDefaultArgs($function, (array)$rule['constructorArgs'], $rule);
422 3
                $factory = function ($args) use ($callback, $callbackArgs) {
423 3
                    return call_user_func_array($callback, $this->resolveArgs($callbackArgs, $args));
424
                };
425
            } else {
426
                $factory = $callback;
427
            }
428 37
429 4
            // If a class is specified then still reflect on it so that calls can be made against it.
430
            if (class_exists($className)) {
431
                $class = new \ReflectionClass($className);
432 4
            }
433 4
        } else {
434 4
            // The instance is created by newing up a class.
435 4
            if (!class_exists($className)) {
436 4
                throw new NotFoundException("Class $className does not exist.", 404);
437
            }
438
            $class = new \ReflectionClass($className);
439 4
            $constructor = $class->getConstructor();
440 4
441
            if ($constructor && $constructor->getNumberOfParameters() > 0) {
442 4
                $constructorArgs = $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs'], $rule);
443 4
444 4
                $factory = function ($args) use ($className, $constructorArgs) {
445 4
                    return new $className(...array_values($this->resolveArgs($constructorArgs, $args)));
446 4
                };
447 4
            } else {
448
                $factory = function () use ($className) {
449 4
                    return new $className;
450 4
                };
451 4
            }
452
        }
453 37
454
        // Add calls to the factory.
455
        if (isset($class) && !empty($rule['calls'])) {
456
            $calls = [];
457
458
            // Generate the calls array.
459
            foreach ($rule['calls'] as $call) {
460
                list($methodName, $args) = $call;
461
                $method = $class->getMethod($methodName);
462
                $calls[] = [$methodName, $this->makeDefaultArgs($method, $args, $rule)];
463
            }
464
465
            // Wrap the factory in one that makes the calls.
466
            $factory = function ($args) use ($factory, $calls) {
467 16
                $instance = $factory($args);
468 16
469
                foreach ($calls as $call) {
470 3
                    call_user_func_array(
471 3
                        [$instance, $call[0]],
472
                        $this->resolveArgs($call[1], [], $instance)
473 3
                    );
474 1
                }
475 1
476
                return $instance;
477 1
            };
478
        }
479 1
480 1
        return $factory;
481 1
    }
482 2
483
    /**
484
     * Create a shared instance of a class from a rule.
485
     *
486 3
     * This method has the side effect of adding the new instance to the internal instances array of this object.
487 2
     *
488 2
     * @param string $nid The normalized ID of the container item.
489 3
     * @param array $rule The resolved rule for the ID.
490 13
     * @param array $args Additional arguments passed during creation.
491 13
     * @return object Returns the the new instance.
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double|string|nu...boolean|resource|object?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
492 1
     * @throws NotFoundException Throws an exception if the class does not exist.
493
     */
494 12
    private function createSharedInstance($nid, array $rule, array $args) {
495 12
        if (!empty($rule['factory'])) {
496
            // The instance is created with a user-supplied factory function.
497 12
            $callback = $rule['factory'];
498
            $function = $this->reflectCallback($callback);
499 11
500
            if ($function->getNumberOfParameters() > 0) {
501 11
                $callbackArgs = $this->resolveArgs(
502 11
                    $this->makeDefaultArgs($function, (array)$rule['constructorArgs'], $rule),
503
                    $args
504 11
                );
505 11
506 11
                $this->instances[$nid] = null; // prevent cyclic dependency from infinite loop.
507 1
                $this->instances[$nid] = $instance = call_user_func_array($callback, $callbackArgs);
508
            } else {
509
                $this->instances[$nid] = $instance = $callback();
510
            }
511
512 15
            // Reflect on the instance so that calls can be made against it.
513 2
            if (is_object($instance)) {
514 2
                $class = new \ReflectionClass(get_class($instance));
515 2
            }
516
        } else {
517 2
            $className = empty($rule['class']) ? $nid : $rule['class'];
518 2
            if (!class_exists($className)) {
519 2
                throw new NotFoundException("Class $className does not exist.", 404);
520
            }
521 2
            $class = new \ReflectionClass($className);
522
            $constructor = $class->getConstructor();
523 2
524 2
            if ($constructor && $constructor->getNumberOfParameters() > 0) {
525 2
                // Instantiate the object first so that this instance can be used for cyclic dependencies.
526
                $this->instances[$nid] = $instance = $class->newInstanceWithoutConstructor();
527 15
528
                $constructorArgs = $this->resolveArgs(
529
                    $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs'], $rule),
530
                    $args
531
                );
532
                $constructor->invokeArgs($instance, $constructorArgs);
533
            } else {
534
                $this->instances[$nid] = $instance = new $class->name;
535
            }
536
        }
537
538 46
        // Call subsequent calls on the new object.
539 46
        if (isset($class) && !empty($rule['calls'])) {
540 46
            foreach ($rule['calls'] as $call) {
541
                list($methodName, $args) = $call;
542 46
                $method = $class->getMethod($methodName);
543 46
544 46
                $args = $this->resolveArgs(
545
                    $this->makeDefaultArgs($method, $args, $rule),
546 46
                    [],
547 2
                    $instance
548 46
                );
549 44
550 44
                $method->invokeArgs($instance, $args);
551 44
            }
552 9
        }
553 44
554 17
        return $instance;
555 17
    }
556 43
557 24
    /**
558 24
     * Make an array of default arguments for a given function.
559 5
     *
560
     * @param \ReflectionFunctionAbstract $function The function to make the arguments for.
561
     * @param array $ruleArgs An array of default arguments specifically for the function.
562 46
     * @param array $rule The entire rule.
563 46
     * @return array Returns an array in the form `name => defaultValue`.
564
     */
565 46
    private function makeDefaultArgs(\ReflectionFunctionAbstract $function, array $ruleArgs, array $rule = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $rule is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
566
        $ruleArgs = array_change_key_case($ruleArgs);
567
        $result = [];
568
569
        $pos = 0;
570
        foreach ($function->getParameters() as $i => $param) {
571
            $name = strtolower($param->name);
572
573
            if (array_key_exists($name, $ruleArgs)) {
574
                $value = $ruleArgs[$name];
575
            } elseif ($param->getClass()
576
                && !(isset($ruleArgs[$pos]) && is_object($ruleArgs[$pos]) && get_class($ruleArgs[$pos]) === $param->getClass()->name)
577 46
                && ($param->getClass()->isInstantiable() || isset($this->rules[$param->getClass()->name]) || array_key_exists($param->getClass()->name, $this->instances))
578 46
            ) {
579
                $value = new DefaultReference($this->normalizeID($param->getClass()->name));
580 46
            } elseif (array_key_exists($pos, $ruleArgs)) {
581 46
                $value = $ruleArgs[$pos];
582 46
                $pos++;
583
            } elseif ($param->isDefaultValueAvailable()) {
584 2
                $value = $param->getDefaultValue();
585 46
            } else {
586
                $value = new RequiredParameter($param);
587 6
            }
588 6
589 6
            $result[$name] = $value;
590
        }
591 41
592
        return $result;
593
    }
594 46
595 12
    /**
596 10
     * Replace an array of default args with called args.
597
     *
598 44
     * @param array $defaultArgs The default arguments from {@link Container::makeDefaultArgs()}.
599 44
     * @param array $args The arguments passed into a creation.
600
     * @param mixed $instance An object instance if the arguments are being resolved on an already constructed object.
601 44
     * @return array Returns an array suitable to be applied to a function call.
602
     * @throws MissingArgumentException Throws an exception when a required parameter is missing.
603
     */
604
    private function resolveArgs(array $defaultArgs, array $args, $instance = null) {
605
        $args = array_change_key_case($args);
606
607
        $pos = 0;
608
        foreach ($defaultArgs as $name => &$default) {
609
            if (array_key_exists($name, $args)) {
610
                // This is a named arg and should be used.
611
                $value = $args[$name];
612
            } elseif (isset($args[$pos]) && (!($default instanceof DefaultReference) || empty($default->getClass()) || is_a($args[$pos], $default->getClass()))) {
613 53
                // There is an arg at this position and it's the same type as the default arg or the default arg is typeless.
614 53
                $value = $args[$pos];
615
                $pos++;
616
            } else {
617 53
                // There is no passed arg, so use the default arg.
618 38
                $value = $default;
619 37
            }
620 35
621 35
            if ($value instanceof ReferenceInterface) {
622 16
                $value = $value->resolve($this, $instance);
623
            }
624 49
625
            $default = $value;
626
        }
627
628
        return $defaultArgs;
629
    }
630
631
    /**
632
     * Create an instance of a container item.
633
     *
634
     * This method either creates a new instance or returns an already created shared instance.
635 3
     *
636 3
     * @param string $nid The normalized ID of the container item.
637
     * @param array $args Additional arguments to pass to the constructor.
638 3
     * @return object Returns an object instance.
639 1
     */
640
    private function createInstance($nid, array $args) {
641 1
        $rule = $this->makeRule($nid);
642 1
643 1
        // Cache the instance or its factory for future use.
644 1
        if (empty($rule['shared'])) {
645 2
            $factory = $this->makeFactory($nid, $rule);
646
            $instance = $factory($args);
647
            $this->factories[$nid] = $factory;
648 3
        } else {
649
            $instance = $this->createSharedInstance($nid, $rule, $args);
650 3
        }
651
        return $instance;
652
    }
653
654
    /**
655
     * Call a callback with argument injection.
656
     *
657
     * @param callable $callback The callback to call.
658
     * @param array $args Additional arguments to pass to the callback.
659
     * @return mixed Returns the result of the callback.
660 5
     * @throws ContainerException Throws an exception if the callback cannot be understood.
661 5
     */
662
    public function call(callable $callback, array $args = []) {
663 5
        $instance = null;
664
665
        if (is_array($callback)) {
666
            $function = new \ReflectionMethod($callback[0], $callback[1]);
667
668
            if (is_object($callback[0])) {
669
                $instance = $callback[0];
670
            }
671
        } else {
672 4
            $function = new \ReflectionFunction($callback);
673 4
        }
674 4
675
        $args = $this->resolveArgs($this->makeDefaultArgs($function, $args), [], $instance);
676
677
        return call_user_func_array($callback, $args);
678
    }
679
680
    /**
681
     * Returns true if the container can return an entry for the given identifier. Returns false otherwise.
682
     *
683
     * @param string $id Identifier of the entry to look for.
684
     *
685
     * @return boolean
686
     */
687 50
    public function has($id) {
688 50
        $id = $this->normalizeID($id);
689
690
        return isset($this->instances[$id]) || !empty($this->rules[$id]) || class_exists($id);
691
    }
692
693
    /**
694
     * Determines whether a rule has been defined at a given ID.
695
     *
696
     * @param string $id Identifier of the entry to look for.
697 9
     * @return bool Returns **true** if a rule has been defined or **false** otherwise.
698 9
     */
699 2
    public function hasRule($id) {
700
        $id = $this->normalizeID($id);
701 7
        return !empty($this->rules[$id]);
702
    }
703
704
    /**
705
     * Finds an entry of the container by its identifier and returns it.
706
     *
707
     * @param string $id Identifier of the entry to look for.
708
     *
709
     * @throws NotFoundException  No entry was found for this identifier.
710
     * @throws ContainerException Error while retrieving the entry.
711
     *
712
     * @return mixed Entry.
713
     */
714
    public function get($id) {
715
        return $this->getArgs($id);
716
    }
717
718
    /**
719
     * Determine the reflection information for a callback.
720
     *
721
     * @param callable $callback The callback to reflect.
722
     * @return \ReflectionFunctionAbstract Returns the reflection function for the callback.
723
     */
724
    private function reflectCallback(callable $callback) {
725
        if (is_array($callback)) {
726
            return new \ReflectionMethod($callback[0], $callback[1]);
727
        } else {
728
            return new \ReflectionFunction($callback);
729
        }
730
    }
731
}
732