ServiceProviderManager::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 6
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Habemus\ServiceProvider;
5
6
use Habemus\Container;
7
use Habemus\ServiceProvider\LazyServiceProvider;
8
use Habemus\ServiceProvider\ServiceProvider;
9
use SplObjectStorage;
10
11
class ServiceProviderManager
12
{
13
    /**
14
     * @var Container
15
     */
16
    protected $container;
17
18
    /**
19
     * @var SplObjectStorage
20
     */
21
    protected $providers;
22
23
    /**
24
     * @var SplObjectStorage
25
     */
26
    protected $lazyProviders;
27
28
    public function __construct(Container $container, ServiceProvider ...$providers)
29
    {
30
        $this->lazyProviders = new SplObjectStorage();
31
        $this->providers = new SplObjectStorage();
32
        $this->container = $container;
33
        $this->add(...$providers);
34
    }
35
36
    public function add(ServiceProvider ...$providers): void
37
    {
38
        foreach ($providers as $provider) {
39
            if ($this->providers->contains($provider)) {
40
                continue;
41
            }
42
43
            $this->providers->attach($provider);
44
            if ($provider instanceof LazyServiceProvider) {
45
                $this->lazyProviders->attach($provider);
46
            } else {
47
                $provider->register($this->container);
48
            }
49
        }
50
    }
51
52
    public function registerLazyProviderFor(string $id): void
53
    {
54
        foreach ($this->lazyProviders as $provider) {
55
            if ($provider->provides($id)) {
56
                $provider->register($this->container);
57
                $this->lazyProviders->detach($provider);
58
                break;
59
            }
60
        }
61
    }
62
63
    public function provides(string $id): bool
64
    {
65
        foreach ($this->lazyProviders as $provider) {
66
            if ($provider->provides($id)) {
67
                return true;
68
            }
69
        }
70
71
        return false;
72
    }
73
74
    public function count(): int
75
    {
76
        return count($this->providers);
77
    }
78
}
79