DriverLinker   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 20
c 2
b 0
f 0
dl 0
loc 52
rs 10
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A update() 0 4 2
A linkTimer() 0 10 2
A link() 0 9 2
A assertDriverCanBeLinked() 0 7 3
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