1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace League\Container\ServiceProvider; |
6
|
|
|
|
7
|
|
|
use Generator; |
8
|
|
|
use League\Container\Exception\ContainerException; |
9
|
|
|
use League\Container\{ContainerAwareInterface, ContainerAwareTrait}; |
10
|
|
|
|
11
|
|
|
class ServiceProviderAggregate implements ServiceProviderAggregateInterface |
12
|
|
|
{ |
13
|
|
|
use ContainerAwareTrait; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var ServiceProviderInterface[] |
17
|
|
|
*/ |
18
|
|
|
protected $providers = []; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var array |
22
|
|
|
*/ |
23
|
|
|
protected $registered = []; |
24
|
|
|
|
25
|
18 |
|
public function add(ServiceProviderInterface $provider): ServiceProviderAggregateInterface |
26
|
|
|
{ |
27
|
18 |
|
if (in_array($provider, $this->providers, true)) { |
28
|
3 |
|
return $this; |
29
|
|
|
} |
30
|
|
|
|
31
|
18 |
|
$provider->setContainer($this->getContainer()); |
32
|
|
|
|
33
|
18 |
|
if ($provider instanceof BootableServiceProviderInterface) { |
34
|
9 |
|
$provider->boot(); |
35
|
|
|
} |
36
|
|
|
|
37
|
18 |
|
$this->providers[] = $provider; |
38
|
18 |
|
return $this; |
39
|
|
|
} |
40
|
|
|
|
41
|
39 |
|
public function provides(string $service): bool |
42
|
|
|
{ |
43
|
39 |
|
foreach ($this->getIterator() as $provider) { |
44
|
15 |
|
if ($provider->provides($service)) { |
45
|
15 |
|
return true; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
24 |
|
return false; |
50
|
|
|
} |
51
|
|
|
|
52
|
42 |
|
public function getIterator(): Generator |
53
|
|
|
{ |
54
|
42 |
|
yield from $this->providers; |
55
|
|
|
} |
56
|
|
|
|
57
|
15 |
|
public function register(string $service): void |
58
|
|
|
{ |
59
|
15 |
|
if (false === $this->provides($service)) { |
60
|
3 |
|
throw new ContainerException( |
61
|
3 |
|
sprintf('(%s) is not provided by a service provider', $service) |
62
|
3 |
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
12 |
|
foreach ($this->getIterator() as $provider) { |
66
|
12 |
|
if (in_array($provider->getIdentifier(), $this->registered, true)) { |
67
|
3 |
|
continue; |
68
|
|
|
} |
69
|
|
|
|
70
|
12 |
|
if ($provider->provides($service)) { |
71
|
12 |
|
$provider->register(); |
72
|
12 |
|
$this->registered[] = $provider->getIdentifier(); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|