-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathSynchronousAdapter.php
More file actions
103 lines (81 loc) · 2.59 KB
/
SynchronousAdapter.php
File metadata and controls
103 lines (81 loc) · 2.59 KB
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
<?php
declare(strict_types=1);
namespace Yiisoft\Queue\Adapter;
use BackedEnum;
use InvalidArgumentException;
use Yiisoft\Queue\ChannelNormalizer;
use Yiisoft\Queue\JobStatus;
use Yiisoft\Queue\Message\MessageInterface;
use Yiisoft\Queue\Provider\QueueProviderInterface;
use Yiisoft\Queue\QueueInterface;
use Yiisoft\Queue\Worker\WorkerInterface;
use Yiisoft\Queue\Message\IdEnvelope;
use function count;
final class SynchronousAdapter implements AdapterInterface
{
private array $messages = [];
private int $current = 0;
private string $channel;
public function __construct(
private readonly WorkerInterface $worker,
private readonly QueueInterface $queue,
string|BackedEnum $channel = QueueProviderInterface::DEFAULT_CHANNEL,
) {
$this->channel = ChannelNormalizer::normalize($channel);
}
public function __destruct()
{
$this->runExisting(function (MessageInterface $message): bool {
$this->worker->process($message, $this->queue);
return true;
});
}
public function runExisting(callable $handlerCallback): void
{
$result = true;
while (isset($this->messages[$this->current]) && $result === true) {
$result = $handlerCallback($this->messages[$this->current]);
unset($this->messages[$this->current]);
$this->current++;
}
}
public function status(string|int $id): JobStatus
{
$id = (int) $id;
if ($id < 0) {
throw new InvalidArgumentException('This adapter IDs start with 0.');
}
if ($id < $this->current) {
return JobStatus::DONE;
}
if (isset($this->messages[$id])) {
return JobStatus::WAITING;
}
throw new InvalidArgumentException('There is no message with the given ID.');
}
public function push(MessageInterface $message): MessageInterface
{
$key = count($this->messages) + $this->current;
$this->messages[] = $message;
return new IdEnvelope($message, $key);
}
public function subscribe(callable $handlerCallback): void
{
$this->runExisting($handlerCallback);
}
public function withChannel(string|BackedEnum $channel): self
{
$channel = ChannelNormalizer::normalize($channel);
if ($channel === $this->channel) {
return $this;
}
$new = clone $this;
$new->channel = $channel;
$new->messages = [];
return $new;
}
public function getChannel(): string
{
return $this->channel;
}
}