summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/scheduler/src/Common/Timers.php
blob: 2d0641fc8fa7a96824ab44fb0398cbb53e13b9f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

namespace ipl\Scheduler\Common;

use Ramsey\Uuid\UuidInterface;
use React\EventLoop\TimerInterface;
use SplObjectStorage;

trait Timers
{
    /** @var SplObjectStorage<UuidInterface, TimerInterface> */
    protected $timers;

    /**
     * Set a timer for the given UUID
     *
     * **Example Usage:**
     *
     * ```php
     * $timers->attachTimer($uuid, Loop::addTimer($interval, $callback));
     * ```
     *
     * @param UuidInterface $uuid
     * @param TimerInterface $timer
     *
     * @return $this
     */
    protected function attachTimer(UuidInterface $uuid, TimerInterface $timer): self
    {
        $this->timers->attach($uuid, $timer);

        return $this;
    }

    /**
     * Detach and return the timer for the given UUID, if any
     *
     * **Example Usage:**
     *
     * ```php
     * Loop::cancelTimer($timers->detachTimer($uuid));
     * ```
     *
     * @param UuidInterface $uuid
     *
     * @return ?TimerInterface
     */
    protected function detachTimer(UuidInterface $uuid): ?TimerInterface
    {
        if (! $this->timers->contains($uuid)) {
            return null;
        }

        $timer = $this->timers->offsetGet($uuid);

        $this->timers->detach($uuid);

        return $timer;
    }
}