Completed
Pull Request — master (#4)
by Joao
01:19
created

Container   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 71
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B get() 0 25 6
A has() 0 4 1
A raw() 0 8 2
1
<?php
2
3
namespace ByJG\Config;
4
5
use ByJG\Config\Exception\KeyNotFoundException;
6
use Closure;
7
use Psr\Container\ContainerInterface;
8
use ReflectionException;
9
10
class Container implements ContainerInterface
11
{
12
    private $config = [];
13
14
    public function __construct($config)
15
    {
16
        $this->config = $config;
17
    }
18
19
    /**
20
     * Finds an entry of the container by its identifier and returns it.
21
     *
22
     * @param string $id Identifier of the entry to look for.
23
     * @return mixed Entry.
24
     * @throws KeyNotFoundException
25
     * @throws ReflectionException
26
     */
27
    public function get($id)
28
    {
29
        $value = $this->raw($id);
30
31
        if ($value instanceof DependencyInjection) {
32
            $value->injectContainer($this);
33
            return $value->getInstance();
34
        }
35
36
        if (!($value instanceof Closure)) {
37
            return $value;
38
        }
39
40
        $args = array_slice(func_get_args(), 1);
41
42
        if (count($args) === 1 && is_array($args[0])) {
43
            $args = $args[0];
44
        }
45
46
        if (empty($args)) {
47
            $args = [];
48
        }
49
50
        return call_user_func_array($value, $args);
51
    }
52
53
    /**
54
     * Returns true if the container can return an entry for the given identifier.
55
     * Returns false otherwise.
56
     * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
57
     * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
58
     *
59
     * @param string $id Identifier of the entry to look for.
60
     * @return bool
61
     */
62
    public function has($id)
63
    {
64
        return isset($this->config[$id]);
65
    }
66
67
    /**
68
     * @param $id
69
     * @return mixed
70
     * @throws KeyNotFoundException
71
     */
72
    public function raw($id)
73
    {
74
        if (!$this->has($id)) {
75
            throw new KeyNotFoundException("The key '$id' does not exists");
76
        }
77
78
        return $this->config[$id];
79
    }
80
}
81