TimersAware::getEventLoop()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 1
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the slince/spike package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Spike\Common\Timer;
13
14
use React\EventLoop\LoopInterface;
15
16
trait TimersAware
17
{
18
    /**
19
     * Array of timers.
20
     *
21
     * @var TimerInterface[]
22
     */
23
    private $timers = [];
24
25
    /**
26
     * @var array
27
     */
28
    private $reactTimers = [];
29
30
    /**
31
     * Add one timer.
32
     *
33
     * @param TimerInterface $timer
34
     */
35
    public function addTimer(TimerInterface $timer)
36
    {
37
        $eventLoop = $this->getEventLoop();
38
        if ($timer->isPeriodic()) {
39
            $reactTimer = $eventLoop->addPeriodicTimer($timer->getInterval(), $timer);
40
        } else {
41
            $reactTimer = $eventLoop->addTimer($timer->getInterval(), $timer);
42
        }
43
        $this->timers[] = $timer;
44
        $this->reactTimers[spl_object_hash($timer)] = $reactTimer;
45
    }
46
47
    /**
48
     * Cancel Timer.
49
     *
50
     * @param TimerInterface $timer
51
     */
52
    public function cancelTimer(TimerInterface $timer)
53
    {
54
        $id = spl_object_hash($timer);
55
        if (isset($this->reactTimers[$id])) {
56
            $this->getEventLoop()->cancelTimer($this->reactTimers[$id]);
57
        }
58
    }
59
60
    /**
61
     * @return TimerInterface[]
62
     */
63
    public function getTimers()
64
    {
65
        return $this->timers;
66
    }
67
68
    /**
69
     * Gets the loop instance.
70
     *
71
     * @return LoopInterface
72
     */
73
    abstract public function getEventLoop();
74
}