Passed
Push — master ( de3d61...be839c )
by Alec
13:42 queued 13s
created

LoopProbeFactory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 46
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A isALoopProbeClass() 0 3 1
A registerProbes() 0 6 4
A getProbe() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Asynchronous\Factory;
6
7
use AlecRabbit\Spinner\Core\Contract\Loop\Contract\ILoopProbe;
8
use AlecRabbit\Spinner\Core\Factory\Contract\ILoopProbeFactory;
9
use AlecRabbit\Spinner\Exception\DomainException;
10
use ArrayObject;
11
use Traversable;
12
13
final class LoopProbeFactory implements ILoopProbeFactory
14
{
15
    /** @var ArrayObject<int, class-string<ILoopProbe>> $loopProbes */
16
    private ArrayObject $loopProbes;
17
18
    /**
19
     * @param Traversable<class-string<ILoopProbe>> $loopProbes
20
     */
21
    public function __construct(
22
        Traversable $loopProbes,
23
    ) {
24
        $this->loopProbes = new ArrayObject([]);
25
        $this->registerProbes($loopProbes);
26
    }
27
28
    /**
29
     * @param Traversable<class-string<ILoopProbe>> $loopProbes
30
     */
31
    private function registerProbes(Traversable $loopProbes): void
32
    {
33
        /** @var class-string<ILoopProbe> $loopProbe */
34
        foreach ($loopProbes as $loopProbe) {
35
            if (self::isALoopProbeClass($loopProbe) && $loopProbe::isSupported()) {
36
                $this->loopProbes->append($loopProbe);
37
            }
38
        }
39
    }
40
41
    private static function isALoopProbeClass(string $loopProbe): bool
42
    {
43
        return is_subclass_of($loopProbe, ILoopProbe::class);
44
    }
45
46
    public function getProbe(): ILoopProbe
47
    {
48
        /** @var class-string<ILoopProbe> $loopProbe */
49
        foreach ($this->loopProbes as $loopProbe) {
50
            if ($loopProbe::isSupported()) {
51
                return new $loopProbe();
52
            }
53
        }
54
        throw new DomainException(
55
            'No supported event loop found.'
56
            . ' Check that you have installed one of the supported event loops.'
57
            . ' Check your probes list if you have modified it.'
58
            . ' If yoy what to use library in synchronous mode, set option explicitly.'
59
        );
60
    }
61
}
62