|
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()); |
|
|
|
|
|
|
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 |
|
|
|
|
|
|
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
|
|
|
|