DriverLinker::assertDriverCanBeLinked()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AlecRabbit\Spinner\Core;
6
7
use AlecRabbit\Spinner\Contract\ISubject;
8
use AlecRabbit\Spinner\Core\Contract\IDriver;
9
use AlecRabbit\Spinner\Core\Contract\IDriverLinker;
10
use AlecRabbit\Spinner\Core\Loop\Contract\ILoop;
11
use AlecRabbit\Spinner\Exception\DriverCanNotBeReplaced;
12
use AlecRabbit\Spinner\Exception\LogicException;
13
14
final class DriverLinker implements IDriverLinker
15
{
16
    private mixed $renderTimer = null;
17
    private ?IDriver $driver = null;
18
19
    public function __construct(
20
        private readonly ILoop $loop,
21
    ) {
22
    }
23
24
    public function link(IDriver $driver): void
25
    {
26
        $this->assertDriverCanBeLinked($driver);
27
28
        $this->linkTimer($driver);
29
30
        if ($this->driver === null) {
31
            $this->driver = $driver;
32
            $driver->attach($this);
33
        }
34
    }
35
36
    /**
37
     * @throws LogicException
38
     */
39
    private function assertDriverCanBeLinked(IDriver $driver): void
40
    {
41
        if ($this->driver === null || $this->driver === $driver) {
42
            return;
43
        }
44
        throw new DriverCanNotBeReplaced(
45
            'Other instance of driver is already linked.'
46
        );
47
    }
48
49
    private function linkTimer(IDriver $driver): void
50
    {
51
        if ($this->renderTimer) {
52
            $this->loop->cancel($this->renderTimer);
53
        }
54
55
        $this->renderTimer =
56
            $this->loop->repeat(
57
                $driver->getInterval()->toSeconds(),
58
                static fn() => $driver->render(),
59
            );
60
    }
61
62
    public function update(ISubject $subject): void
63
    {
64
        if ($subject === $this->driver) {
0 ignored issues
show
introduced by
The condition $subject === $this->driver is always false.
Loading history...
65
            $this->linkTimer($subject);
66
        }
67
    }
68
}
69