Passed
Push — develop ( 45600c...ff69f6 )
by Paul
03:16
created

Container::has()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
rs 9.2
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace PhpUnitGen\Container;
4
5
use PhpUnitGen\Exception\ContainerException;
6
use PhpUnitGen\Exception\NotFoundException;
7
use Psr\Container\ContainerInterface;
8
9
/**
10
 * Class Container.
11
 *
12
 * @author     Paul Thébaud <[email protected]>.
13
 * @copyright  2017-2018 Paul Thébaud <[email protected]>.
14
 * @license    https://opensource.org/licenses/MIT The MIT license.
15
 * @link       https://github.com/paul-thebaud/phpunit-generator
16
 * @since      Class available since Release 2.0.0.
17
 */
18
class Container implements ContainerInterface
19
{
20
    /**
21
     * @var callable[] $registry All key => resolver.
22
     */
23
    private $registry = [];
24
25
    /**
26
     * @var object[] $instances All already created object instances.
27
     */
28
    private $instances = [];
29
30
    /**
31
     * Save a new key => resolver.
32
     *
33
     * @param string   $key      A key to retrieve the $resolver and the instance.
34
     * @param callable $resolver A resolver which return an object instance.
35
     */
36
    public function setResolver(string $key, callable $resolver): void
37
    {
38
        $this->registry[$key] = $resolver;
39
    }
40
41
    /**
42
     * Save a new instance immediately.
43
     *
44
     * @param string $key      A key to retrieve the instance.
45
     * @param object $instance An object instance to save.
46
     */
47
    public function setInstance(string $key, object $instance): void
48
    {
49
        $this->instances[$key] = $instance;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function get($id): object
56
    {
57
        if (! is_string($id)) {
58
            throw new ContainerException('Given identifier to container is not a string.');
59
        }
60
        if (isset($this->instances[$id])) {
61
            return $this->instances[$id];
62
        }
63
        if (isset($this->registry[$id])) {
64
            return $this->instances[$id] = $this->registry[$id]($this);
65
        }
66
        throw new NotFoundException(sprintf('Identifier "%s" not found in the container.', $id));
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function has($id): bool
73
    {
74
        if (! is_string($id)) {
75
            return false;
76
        }
77
        if (isset($this->instances[$id])) {
78
            return true;
79
        }
80
        if (isset($this->registry[$id])) {
81
            return true;
82
        }
83
        return false;
84
    }
85
}
86