Container   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 52
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B get() 0 31 7
A has() 0 4 2
1
<?php
2
namespace NaiveContainer;
3
4
use NaiveContainer\Exceptions\ContainerException;
5
use NaiveContainer\Exceptions\NotFoundException;
6
use Psr\Container\ContainerInterface;
7
use Exception;
8
9
class Container extends ContainerDecorator implements ContainerInterface
10
{
11
12
    /**
13
     * Instantiated parts
14
     * 
15
     * @var mixed 
16
     */
17
    protected $instances = [];
18
19
    /**
20
     * @var bool[id] 
21
     */
22
    protected $call_stack = [];
23
24
    public function get($id)
25
    {
26
        if (!$this->has($id)) {
27
            throw new NotFoundException("Couldn't find {$id}");
28
        }
29
30
        if (is_callable($this->container_stack[$id])) {
31
            // Performance optimization, isset returns false on null values, but is faster
32
            // https://stackoverflow.com/a/9522522/10604655
33
            if (!isset($this->instances[$id]) && !array_key_exists($id, $this->instances)) {
34
35
                if (isset($this->call_stack[$id])) {
36
                    throw new ContainerException("Circular dependency detected when calling {$id}");
37
                }
38
39
                $this->call_stack[$id] = true;
40
41
                try {
42
                    $this->instances[$id] = call_user_func($this->container_stack[$id], $this);
43
                } catch (Exception $e) {
44
                    throw new ContainerException($e->getMessage() . " - Tried to call {$id}");
45
                }
46
47
                $this->call_stack = [];
48
            }
49
50
            return $this->instances[$id];
51
        }
52
53
        return $this->container_stack[$id];
54
    }
55
56
    public function has($id): bool
57
    {
58
        return (isset($this->container_stack[$id]) || array_key_exists($id, $this->container_stack));
59
    }
60
}
61