-
Notifications
You must be signed in to change notification settings - Fork 2
/
GearmanConsumer.php
106 lines (86 loc) · 2.11 KB
/
GearmanConsumer.php
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
declare(strict_types=1);
namespace Enqueue\Gearman;
use Interop\Queue\Consumer;
use Interop\Queue\Message;
use Interop\Queue\Queue;
class GearmanConsumer implements Consumer
{
/**
* @var \GearmanWorker
*/
private $worker;
/**
* @var GearmanDestination
*/
private $destination;
/**
* @var GearmanContext
*/
private $context;
/**
* Message content.
*
* @var mixed
*/
private $message;
public function __construct(GearmanContext $context, GearmanDestination $destination)
{
$this->context = $context;
$this->destination = $destination;
$this->worker = $context->createWorker();
$this->worker->addFunction($this->destination->getName(), function (\GearmanJob $job) {
$this->message = GearmanMessage::jsonUnserialize($job->workload());
});
}
/**
* @return GearmanDestination
*/
public function getQueue(): Queue
{
return $this->destination;
}
/**
* @return GearmanMessage
*/
public function receive(int $timeout = 0): ?Message
{
set_error_handler(function ($severity, $message, $file, $line) {
throw new \ErrorException($message, 0, $severity, $file, $line);
});
$this->worker->setTimeout($timeout);
try {
$this->message = null;
$this->worker->work();
} finally {
restore_error_handler();
}
return $this->message;
}
/**
* @return GearmanMessage
*/
public function receiveNoWait(): ?Message
{
return $this->receive(100);
}
/**
* @param GearmanMessage $message
*/
public function acknowledge(Message $message): void
{
}
/**
* @param GearmanMessage $message
*/
public function reject(Message $message, bool $requeue = false): void
{
if ($requeue) {
$this->context->createProducer()->send($this->destination, $message);
}
}
public function getWorker(): \GearmanWorker
{
return $this->worker;
}
}