Completed
Push — master ( bf916e...aae4af )
by Phil
02:39
created

ServiceProviderAggregate::register()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 24
ccs 15
cts 15
cp 1
rs 8.6845
cc 4
eloc 12
nc 5
nop 1
crap 4
1
<?php
2
3
namespace League\Container\ServiceProvider;
4
5
use League\Container\ContainerAwareInterface;
6
use League\Container\ContainerAwareTrait;
7
8
class ServiceProviderAggregate implements ServiceProviderAggregateInterface
9
{
10
    use ContainerAwareTrait;
11
12
    /**
13
     * @var array
14
     */
15
    protected $providers = [];
16
17
    /**
18
     * @var array
19
     */
20
    protected $registered = [];
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 21
    public function add($provider)
26
    {
27 21
        if (is_string($provider) && class_exists($provider)) {
28 3
            $provider = new $provider;
29 3
        }
30
31 21
        if ($provider instanceof ContainerAwareInterface) {
32 18
            $provider->setContainer($this->getContainer());
33 18
        }
34
35 21
        if ($provider instanceof BootableServiceProviderInterface) {
36 9
            $provider->boot();
37 9
        }
38
39 21
        if ($provider instanceof ServiceProviderInterface) {
40 18
            foreach ($provider->provides() as $service) {
41 18
                $this->providers[$service] = $provider;
42 18
            }
43
44 18
            return $this;
45
        }
46
47 3
        throw new \InvalidArgumentException(
48
            'A service provider must be a fully qualified class name or instance ' .
49
            'of (\League\Container\ServiceProvider\ServiceProviderInterface)'
50 3
        );
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 33
    public function provides($service)
57
    {
58 33
        return array_key_exists($service, $this->providers);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 18
    public function register($service)
65
    {
66 18
        if (! array_key_exists($service, $this->providers)) {
67 3
            throw new \InvalidArgumentException(
68 3
                sprintf('(%s) is not provided by a service provider', $service)
69 3
            );
70
        }
71
72 15
        $provider  = $this->providers[$service];
73 15
        $signature = get_class($provider);
74
75 15
        if ($provider instanceof SignatureServiceProviderInterface) {
76 3
            $signature = $provider->getSignature();
77 3
        }
78
79
        // ensure that the provider hasn't already been invoked by any other service request
80 15
        if (in_array($signature, $this->registered)) {
81 6
            return;
82
        }
83
84 15
        $provider->register();
85
86 15
        $this->registered[] = $signature;
87 15
    }
88
}
89