|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Created by PhpStorm. |
|
4
|
|
|
* User: james |
|
5
|
|
|
* Date: 23/07/2018 |
|
6
|
|
|
* Time: 20:17 |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Specter\Container; |
|
10
|
|
|
|
|
11
|
|
|
use Psr\Container\ContainerInterface; |
|
12
|
|
|
use Specter\Container\Exceptions\DuplicateServiceException; |
|
13
|
|
|
use Specter\Container\Exceptions\ServiceNotFoundException; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class Container |
|
17
|
|
|
* @package Specter\Container |
|
18
|
|
|
* @author James Parker <[email protected]> |
|
19
|
|
|
*/ |
|
20
|
|
|
class Container implements ContainerInterface |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* An array of all the container resources |
|
24
|
|
|
* |
|
25
|
|
|
* @var array |
|
26
|
|
|
*/ |
|
27
|
|
|
private $resources = []; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Returns true if the container can return an entry for the given identifier. |
|
31
|
|
|
* Returns false otherwise. |
|
32
|
|
|
* @param string $id |
|
33
|
|
|
* |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
|
|
public function has($id) |
|
37
|
|
|
{ |
|
38
|
|
|
return array_key_exists($id, $this->resources); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Finds a service from the container. |
|
43
|
|
|
* If the service is not found a ServiceNotFoundException will be thrown. |
|
44
|
|
|
* |
|
45
|
|
|
* @param string $id |
|
46
|
|
|
* @return mixed |
|
47
|
|
|
* |
|
48
|
|
|
* @throws ServiceNotFoundException |
|
49
|
|
|
*/ |
|
50
|
|
|
public function get($id) |
|
51
|
|
|
{ |
|
52
|
|
|
if (!$this->has($id)) { |
|
53
|
|
|
//@codeCoverageIgnoreStart |
|
54
|
|
|
throw new ServiceNotFoundException($id); |
|
55
|
|
|
//@codeCoverageIgnoreEnd |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $this->resources[$id]; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Sets a service to the container. |
|
63
|
|
|
* if the resource already exists, then it will thrown an exception. |
|
64
|
|
|
* |
|
65
|
|
|
* @param string $id the ID of the service. |
|
66
|
|
|
* @param mixed $service the service to set. |
|
67
|
|
|
* |
|
68
|
|
|
* @return void |
|
69
|
|
|
* @throws DuplicateServiceException |
|
70
|
|
|
*/ |
|
71
|
|
|
public function set($id, $service) |
|
72
|
|
|
{ |
|
73
|
|
|
if ($this->has($id)) { |
|
74
|
|
|
//@codeCoverageIgnoreStart |
|
75
|
|
|
throw new DuplicateServiceException($id); |
|
76
|
|
|
//@codeCoverageIgnoreEnd |
|
77
|
|
|
} |
|
78
|
|
|
$this->resources[$id] = $service; |
|
79
|
|
|
|
|
80
|
|
|
} |
|
81
|
|
|
} |