Container::set()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
namespace DelayQueue\Container;
4
5
use Closure;
6
use ArrayAccess;
7
use Psr\Container\ContainerInterface;
8
use DelayQueue\Exception\ServiceNotFoundException;
9
10
/**
11
 * 服务容器
12
 */
13
class Container implements  ContainerInterface, ArrayAccess
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "ContainerInterface"; 2 found
Loading history...
14
{
15
    /**
16
     * @var array 服务定义
17
     */
18
    protected  $definitions = [];
19
    /**
20
     * @var array 已实例化的服务
21
     */
22
    protected  $instances = [];
23
24
    /**
25
     * 添加服务
26
     *
27
     * @param string  $id       服务唯一标识
28
     * @param Closure $callback
29
     */
30
    public  function set($id, Closure $callback)
31
    {
32
        if ($id) {
33
            $this->definitions[$id] = $callback;
34
        }
35
    }
36
37
    /**
38
     * 查找服务是否存在
39
     *
40
     * @param  string $id 服务唯一标识
41
     * @return bool
42
     */
43
    public function has($id)
44
    {
45
        return isset($this->definitions[$id]);
46
    }
47
48
    /**
49
     * 获取服务
50
     *
51
     * @param  string $id 服务唯一标识
52
     * @return mixed
53
     * @throws ServiceNotFoundException
54
     */
55
    public  function get($id)
56
    {
57
        if (isset($this->instances[$id])) {
58
            return $this->instances[$id];
59
        }
60
61
        if (!isset($this->definitions[$id])) {
62
            $message = sprintf('service [%s] not exists', $id);
63
            throw new ServiceNotFoundException($message);
64
        }
65
66
        /** @var Closure $callback */
67
        $callback = $this->definitions[$id];
68
        $callback = $callback->bindTo($this);
69
70
        $this->instances[$id] = $callback();
71
72
        return $this->instances[$id];
73
    }
74
75
    public function __get($name)
76
    {
77
        return $this->get($name);
78
    }
79
80
    public function __set($name, $value)
81
    {
82
        $this->set($name, $value);
83
    }
84
85
    public function offsetExists($offset)
86
    {
87
        return $this->has($offset);
88
    }
89
90
    public function offsetGet($offset)
91
    {
92
        return $this->get($offset);
93
    }
94
95
    public function offsetSet($offset, $value)
96
    {
97
        $this->set($offset, $value);
98
    }
99
100
    public function offsetUnset($offset)
101
    {
102
        unset($this->definitions[$offset]);
103
        unset($this->instances[$offset]);
104
    }
105
}