Completed
Push — 4.x ( 8fa263...613328 )
by Phil
03:02
created

ServiceProviderAggregate::add()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.7
c 0
b 0
f 0
cc 4
nc 5
nop 1
crap 4
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
        if ($provider instanceof ContainerAwareInterface) {
32 18
            $provider->setContainer($this->getContainer());
33
        }
34
35 18
        if ($provider instanceof BootableServiceProviderInterface) {
36 9
            $provider->boot();
37
        }
38
39 18
        $this->providers[] = $provider;
40 18
        return $this;
41
    }
42
43 30
    public function provides(string $service): bool
44
    {
45 30
        foreach ($this->getIterator() as $provider) {
46 15
            if ($provider->provides($service)) {
47 15
                return true;
48
            }
49
        }
50
51 15
        return false;
52
    }
53
54 33
    public function getIterator(): Generator
55
    {
56 33
        yield from $this->providers;
57 30
    }
58
59 15
    public function register(string $service): void
60
    {
61 15
        if (false === $this->provides($service)) {
62 3
            throw new ContainerException(
63 3
                sprintf('(%s) is not provided by a service provider', $service)
64
            );
65
        }
66
67 12
        foreach ($this->getIterator() as $provider) {
68 12
            if (in_array($provider->getIdentifier(), $this->registered, true)) {
69 3
                continue;
70
            }
71
72 12
            if ($provider->provides($service)) {
73 12
                $provider->register();
74 12
                $this->registered[] = $provider->getIdentifier();
75
            }
76
        }
77 12
    }
78
}
79