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

TerminalProbeFactory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 44
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A registerProbes() 0 6 3
A getProbe() 0 9 3
A getProbeClass() 0 3 1
A isValidProbeClass() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core\Factory;
6
7
use AlecRabbit\Spinner\Contract\IProbe;
8
use AlecRabbit\Spinner\Core\Factory\Contract\ITerminalProbeFactory;
9
use AlecRabbit\Spinner\Core\Terminal\Contract\ITerminalProbe;
10
use AlecRabbit\Spinner\Exception\DomainException;
11
use ArrayObject;
12
use Traversable;
13
14
final class TerminalProbeFactory implements ITerminalProbeFactory
15
{
16
    /** @var Traversable<ITerminalProbe> */
17
    protected Traversable $registeredProbes;
18
19
    public function __construct(
20
        Traversable $probeClasses,
21
    ) {
22
        $this->registeredProbes = new ArrayObject([]);
23
        $this->registerProbes($probeClasses);
24
    }
25
26
    protected function registerProbes(Traversable $probes): void
27
    {
28
        /** @var class-string $probe */
29
        foreach ($probes as $probe) {
30
            if ($this->isValidProbeClass($probe)) {
31
                $this->registeredProbes->append(new $probe());
0 ignored issues
show
Bug introduced by
The method append() does not exist on Traversable. It seems like you code against a sub-type of Traversable such as ArrayObject or AppendIterator or ArrayIterator or RecursiveArrayIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

31
                $this->registeredProbes->/** @scrutinizer ignore-call */ 
32
                                         append(new $probe());
Loading history...
32
            }
33
        }
34
    }
35
36
    private function isValidProbeClass(string $probeClass): bool
37
    {
38
        return is_subclass_of($probeClass, $this->getProbeClass());
39
    }
40
41
    /**
42
     * @return class-string
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
43
     */
44
    protected function getProbeClass(): string
45
    {
46
        return ITerminalProbe::class;
47
    }
48
49
    public function getProbe(): ITerminalProbe
50
    {
51
        /** @var IProbe $probe */
52
        foreach ($this->registeredProbes as $probe) {
53
            if ($probe->isAvailable()) {
54
                return $probe;
55
            }
56
        }
57
        throw new DomainException('No terminal probe found.');
58
    }
59
}
60