ServiceProviderAggregate::add()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 7
c 3
b 0
f 0
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 10
cc 3
nc 3
nop 1
crap 3
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