Passed
Push — master ( 400934...9d586b )
by Anton
02:32
created

DebugBootloader::state()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 24
rs 9.2222
cc 6
nc 9
nop 0
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Bootloader;
13
14
use Spiral\Boot\Bootloader\Bootloader;
15
use Spiral\Core\Container\Autowire;
16
use Spiral\Core\Container\SingletonInterface;
17
use Spiral\Core\FactoryInterface;
18
use Spiral\Debug\Exception\StateException;
19
use Spiral\Debug\State;
20
use Spiral\Debug\StateCollector\EnvironmentCollector;
21
use Spiral\Debug\StateCollectorInterface;
22
use Spiral\Debug\StateInterface;
23
24
final class DebugBootloader extends Bootloader implements SingletonInterface
25
{
26
    protected const SINGLETONS = [
27
        EnvironmentCollector::class => EnvironmentCollector::class
28
    ];
29
30
    protected const BINDINGS = [
31
        StateInterface::class => [self::class, 'state']
32
    ];
33
34
    /** @var StateCollectorInterface[]|string[] */
35
    private $collectors = [];
36
37
    /** @var FactoryInterface */
38
    private $factory;
39
40
    /**
41
     * @param FactoryInterface $factory
42
     */
43
    public function __construct(FactoryInterface $factory)
44
    {
45
        $this->factory = $factory;
46
    }
47
48
    /**
49
     * Boot default state collector.
50
     */
51
    public function boot(): void
52
    {
53
        $this->addStateCollector(EnvironmentCollector::class);
54
    }
55
56
    /**
57
     * @param string|StateCollectorInterface $collector
58
     */
59
    public function addStateCollector($collector): void
60
    {
61
        $this->collectors[] = $collector;
62
    }
63
64
    /**
65
     * Create state and populate it with collectors.
66
     *
67
     * @return StateInterface
68
     */
69
    private function state(): StateInterface
70
    {
71
        $state = new State();
72
73
        foreach ($this->collectors as $collector) {
74
            if (is_string($collector)) {
75
                $collector = $this->factory->make($collector);
76
            }
77
78
            if ($collector instanceof Autowire) {
79
                $collector = $collector->resolve($this->factory);
80
            }
81
82
            if (!$collector instanceof StateCollectorInterface) {
83
                throw new StateException(sprintf(
84
                    'Unable to populate state, invalid state collector %s',
85
                    is_object($collector) ? get_class($collector) : gettype($collector)
86
                ));
87
            }
88
89
            $collector->populate($state);
90
        }
91
92
        return $state;
93
    }
94
}
95