LoopTrait   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 46
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
warning() 0 1 ?
A setLoop() 0 4 1
A getLoop() 0 4 1
A addTimer() 0 4 1
A addPeriodicTimer() 0 4 1
A cancelTimer() 0 4 1
A callable() 0 13 2
1
<?php
2
3
namespace Nopolabs\Yabot\Helpers;
4
5
use React\EventLoop\LoopInterface;
6
use React\EventLoop\Timer\TimerInterface;
7
use Throwable;
8
9
trait LoopTrait
10
{
11
    /** @var LoopInterface */
12
    private $loop;
13
14
    abstract protected function warning($message, array $context = array());
15
16
    protected function setLoop(LoopInterface $loop)
17
    {
18
        $this->loop = $loop;
19
    }
20
21
    protected function getLoop() : LoopInterface
22
    {
23
        return $this->loop;
24
    }
25
26
    protected function addTimer($interval, $function)
27
    {
28
        $this->getLoop()->addTimer($interval, $this->callable($function));
29
    }
30
31
    protected function addPeriodicTimer($interval, $function)
32
    {
33
        $this->getLoop()->addPeriodicTimer($interval, $this->callable($function));
34
    }
35
36
    protected function cancelTimer(TimerInterface $timer)
37
    {
38
        $this->getLoop()->cancelTimer($timer);
39
    }
40
41
    private function callable($function) : callable
42
    {
43
        return function() use ($function) {
44
            try {
45
                call_user_func($function);
46
            } catch (Throwable $throwable) {
47
                $errmsg = "Unhandled Exception in Timer callback\n"
48
                    .$throwable->getMessage()."\n"
49
                    .$throwable->getTraceAsString();
50
                $this->warning($errmsg);
51
            }
52
        };
53
    }
54
}