-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathSynchronousAdapter.php
More file actions
76 lines (59 loc) · 1.91 KB
/
SynchronousAdapter.php
File metadata and controls
76 lines (59 loc) · 1.91 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
<?php
declare(strict_types=1);
namespace Yiisoft\Queue\Adapter;
use InvalidArgumentException;
use Yiisoft\Queue\JobStatus;
use Yiisoft\Queue\Message\MessageInterface;
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;
public function __construct(
private readonly WorkerInterface $worker,
private readonly QueueInterface $queue,
) {}
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);
}
}