Completed
Pull Request — master (#1)
by Joao
02:03
created

Container::getClosure()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace ByJG\Config;
4
5
use ByJG\Config\Exception\NotFoundException;
6
use Psr\Container\ContainerExceptionInterface;
7
use Psr\Container\ContainerInterface;
8
use Psr\Container\NotFoundExceptionInterface;
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
     * @throws NotFoundExceptionInterface  No entry was found for **this** identifier.
24
     * @throws ContainerExceptionInterface Error while retrieving the entry.
25
     * @return mixed Entry.
26
     */
27
    public function get($id)
28
    {
29
        if (!$this->has($id)) {
30
            throw new NotFoundException("The key '$id'' does not exists");
31
        }
32
33
        return $this->config[$id];
34
    }
35
36
    /**
37
     * Returns true if the container can return an entry for the given identifier.
38
     * Returns false otherwise.
39
     * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
40
     * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
41
     *
42
     * @param string $id Identifier of the entry to look for.
43
     * @return bool
44
     */
45
    public function has($id)
46
    {
47
        return isset($this->config[$id]);
48
    }
49
50
    /**
51
     * @param $id
52
     * @param $args
53
     * @return mixed
54
     */
55
    public function getClosure($id, $args = null)
56
    {
57
        $closure = $this->get($id);
58
59
        if (is_array($args)) {
60
            return call_user_func_array($closure, $args);
61
        }
62
63
        return call_user_func_array($closure, array_slice(func_get_args(), 1));
64
    }
65
}
66