Passed
Push — master ( a2340d...9d7d2b )
by butschster
06:32
created

DebugBootloader::addStateCollector()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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