-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServiceRegistry.php
81 lines (67 loc) · 1.94 KB
/
ServiceRegistry.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Registry;
use SonsOfPHP\Component\Registry\Exception\ExistingServiceException;
use SonsOfPHP\Component\Registry\Exception\NonExistingServiceException;
use SonsOfPHP\Contract\Registry\ServiceRegistryInterface;
/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class ServiceRegistry implements ServiceRegistryInterface
{
private array $services = [];
public function __construct(
private readonly string $interface,
) {}
/**
* {@inheritdoc}
*/
public function all(): iterable
{
return $this->services;
}
/**
* {@inheritdoc}
*/
public function register(string $identifier, object $service): void
{
if ($this->has($identifier)) {
throw new ExistingServiceException(sprintf('Service "%s" already exists', $identifier));
}
if (!$service instanceof $this->interface) {
throw new \InvalidArgumentException(sprintf(
'Wrong Service Type. Expected "%s" got "%s"',
$this->interface,
$service::class
));
}
$this->services[$identifier] = $service;
}
/**
* {@inheritdoc}
*/
public function unregister(string $identifier): void
{
if (!$this->has($identifier)) {
throw new NonExistingServiceException(sprintf('Service "%s" does not exist', $identifier));
}
unset($this->services[$identifier]);
}
/**
* {@inheritdoc}
*/
public function has(string $identifier): bool
{
return array_key_exists($identifier, $this->services);
}
/**
* {@inheritdoc}
*/
public function get(string $identifier): object
{
if (!$this->has($identifier)) {
throw new NonExistingServiceException(sprintf('Service "%s" does not exist', $identifier));
}
return $this->services[$identifier];
}
}