Completed
Push — master ( 38f1ea...fd6c7c )
by Matze
04:05
created

Gateway::deleteEvent()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 21
ccs 13
cts 13
cp 1
rs 9.0534
cc 4
eloc 13
nc 4
nop 2
crap 4
1
<?php
2
3
namespace BrainExe\Core\MessageQueue;
4
5
use BrainExe\Annotations\Annotations\Service;
6
use BrainExe\Core\EventDispatcher\AbstractEvent;
7
use BrainExe\Core\Traits\IdGeneratorTrait;
8
use BrainExe\Core\Traits\RedisTrait;
9
use BrainExe\Core\Traits\TimeTrait;
10
use Generator;
11
12
/**
13
 * @api
14
 * @Service("MessageQueue.Gateway", public=false)
15
 */
16
class Gateway
17
{
18
19
    use TimeTrait;
20
    use RedisTrait;
21
    use IdGeneratorTrait;
22
23
    const QUEUE_DELAYED   = 'message_queue:delayed';
24
    const QUEUE_IMMEDIATE = 'message_queue:immediate';
25
    const META_DATA       = 'message_queue:meta_data';
26
    const RETRY_TIME      = 3600; // try again after 1 hour
27
28
    /**
29
     * @param string $eventId
30
     * @param string $eventType
31
     * @return bool success
32
     */
33 3
    public function deleteEvent(string $eventId, string $eventType = null) : bool
34
    {
35 3
        $eventId = sprintf('%s:%s', $eventType, $eventId);
36
37 3
        $redis = $this->getRedis();
38 3
        $delayed = $redis->zrem(self::QUEUE_DELAYED, $eventId);
39 3
        if ($delayed) {
40 1
            $redis->hdel(self::META_DATA, [$eventId]);
41 1
            return true;
42
        }
43
44 2
        $immediate = $this->getRedis()->lrange(self::QUEUE_IMMEDIATE, 0, 100);
45 2
        foreach ($immediate as $rawJob) {
46 1
            list($jobId) = explode('#', $rawJob, 2);
47 1
            if (strpos($jobId, "$eventId") === 0) {
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $eventId instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
48 1
                return (bool)$this->redis->lrem(self::QUEUE_IMMEDIATE, 1, $rawJob);
49
            }
50
        }
51
52 1
        return false;
53
    }
54
55
    /**
56
     * @param AbstractEvent $event
57
     * @param int $timestamp
58
     * @return string
59
     */
60 2
    public function addEvent(AbstractEvent $event, int $timestamp = 0)
61
    {
62 2
        $jobId = $this->generateUniqueId('jobid:' . $event->getEventName());
63 2
        $jobId = sprintf('%s:%s', $event->getEventName(), $jobId);
64
65 2
        $job = new Job($event, $jobId, $timestamp);
66
67 2
        $this->addJob($job);
68 2
    }
69
70
    /**
71
     * @param Job $job
72
     */
73 3
    public function addJob(Job $job)
74
    {
75 3
        $serialized = base64_encode(serialize($job));
76
77 3
        $pipeline = $this->getRedis()->pipeline(['fire-and-forget' => true]);
78 3
        if (empty($job->timestamp)) {
79
            // immediate execution in background
80 1
            $pipeline->lpush(self::QUEUE_IMMEDIATE, $job->jobId . '#' . $serialized);
81
        } else {
82
            // delayed execution
83 2
            $pipeline->hset(self::META_DATA, $job->jobId, $serialized);
84 2
            $pipeline->zadd(self::QUEUE_DELAYED, [
85 2
                $job->jobId => (int)$job->timestamp
86
            ]);
87
        }
88
89 3
        $pipeline->execute();
90 3
    }
91
92
    /**
93
     * @param string $eventType
94
     * @param int $since
95
     * @return Job[]
96
     */
97 3
    public function getEventsByType(string $eventType = null, int $since = 0) : array
98
    {
99 3
        return iterator_to_array($this->getEventsByTypeGenerator($eventType, $since));
100
    }
101
102
    /**
103
     * @param string $eventType
104
     * @param int $since
105
     * @return Generator|Job[]
106
     */
107 3
    public function getEventsByTypeGenerator(string $eventType = null, int $since = 0) : Generator
108
    {
109 3
        $redis = $this->getRedis();
110
111 3
        $resultRaw = $redis->zrangebyscore(
112 3
            self::QUEUE_DELAYED,
113
            $since,
114 3
            '+inf',
115 3
            ['withscores' => true]
116
        );
117
118 3
        $keys = [];
119 3
        foreach ($resultRaw as $jobId => $timestamp) {
120 2
            if (empty($eventType) || strpos($jobId, $eventType . ":") === 0) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal : does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
121 2
                $keys[$jobId] = $timestamp;
122
            }
123
        }
124
125 3
        yield from $this->getFromTimesQueue($keys);
126 3
        yield from $this->getFromImmediateQueue($eventType);
127 3
    }
128
129
    /**
130
     * @param Job $job
131
     */
132 1
    public function restoreJob(Job $job)
133
    {
134 1
        $now = $this->now();
135
136 1
        $job->timestamp = $now + self::RETRY_TIME;
137 1
        $job->errorCounter++;
138 1
        $this->addJob($job);
139 1
    }
140
141
    /**
142
     * @return int
143
     */
144 1
    public function countAllJobs() : int
145
    {
146 1
        $delayed   = $this->getRedis()->zcard(self::QUEUE_DELAYED);
147 1
        $immediate = $this->getRedis()->llen(self::QUEUE_IMMEDIATE);
148
149 1
        return $delayed + $immediate;
150
    }
151
152
    /**
153
     * @param array $keys
154
     * @return Generator
155
     */
156 3
    private function getFromTimesQueue(array $keys) : Generator
157
    {
158 3
        if (!empty($keys)) {
159 2
            $events = $this->getRedis()->hmget(self::META_DATA, array_keys($keys));
160 2
            foreach ($events as $jobId => $rawJob) {
161
                /** @var Job $job */
162 2
                $job = unserialize(base64_decode($rawJob));
163 2
                yield $job->jobId => $job;
164
            }
165
        }
166 3
    }
167
168
    /**
169
     * @param string $eventType
170
     * @return Generator
171
     */
172 3
    private function getFromImmediateQueue(string $eventType = null) : Generator
173
    {
174 3
        $immediate = $this->getRedis()->lrange(self::QUEUE_IMMEDIATE, 0, 100);
175 3
        foreach ($immediate as $rawJob) {
176 1
            list($jobId, $rawJob) = explode('#', $rawJob, 2);
177 1
            if (empty($eventType) || strpos($jobId, $eventType . ":") === 0) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal : does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
178
                /** @var Job $job */
179 1
                $job = unserialize(base64_decode($rawJob));
180 1
                yield $job->jobId => $job;
181
            }
182
        }
183 3
    }
184
}
185