Passed
Push — master ( 823aee...b9b37f )
by Alec
13:15 queued 12s
created

ReactLoopAdapter::attach()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
// 17.02.23
5
6
namespace AlecRabbit\Spinner\Asynchronous\Loop\Adapter;
7
8
use AlecRabbit\Spinner\Asynchronous\Loop\Adapter\A\ALoopAdapter;
9
use AlecRabbit\Spinner\Core\Contract\ISpinner;
10
use Closure;
11
use React\EventLoop\LoopInterface;
12
use React\EventLoop\TimerInterface;
13
14
class ReactLoopAdapter extends ALoopAdapter
15
{
16
    private ?TimerInterface $spinnerTimer = null;
17
18
    public function __construct(
19
        private readonly LoopInterface $loop,
20
    ) {
21
    }
22
23
    public function attach(ISpinner $spinner): void
24
    {
25
        $this->detachSpinner();
26
        $this->spinnerTimer =
27
            $this->loop->addPeriodicTimer(
28
                $spinner->getInterval()->toSeconds(),
29
                static fn() => $spinner->spin()
30
            );
31
    }
32
33
    protected function detachSpinner(): void
34
    {
35
        if ($this->spinnerTimer instanceof TimerInterface) {
36
            $this->loop->cancelTimer($this->spinnerTimer);
37
        }
38
    }
39
40
    public function autoStart(): void
41
    {
42
        // ReactPHP event loop is started by its library code.
43
    }
44
45
    public function repeat(float $interval, Closure $closure): void
46
    {
47
        $this->loop->addPeriodicTimer($interval, $closure);
48
    }
49
50
    public function getLoop(): LoopInterface
51
    {
52
        return $this->loop;
53
    }
54
55
    public function delay(float $delay, Closure $closure): void
56
    {
57
        $this->loop->addTimer($delay, $closure);
58
    }
59
60
    protected function onSignal(int $signal, Closure $closure): void
61
    {
62
        $this->loop->addSignal($signal, $closure);
63
    }
64
}
65