-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathInMemoryAdapter.php
More file actions
87 lines (71 loc) · 2.24 KB
/
Copy pathInMemoryAdapter.php
File metadata and controls
87 lines (71 loc) · 2.24 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
<?php
declare(strict_types=1);
namespace Yiisoft\Queue\Stubs;
use Yiisoft\Queue\Adapter\AdapterInterface;
use Yiisoft\Queue\Message\IdEnvelope;
use Yiisoft\Queue\Message\MessageInterface;
use Yiisoft\Queue\MessageStatus;
use function count;
/**
* In-memory implementation of {@see AdapterInterface} for testing and development purposes.
*
* This adapter stores messages in a local array and processes them sequentially within the same process without any
* external queue backend. Messages are assigned incremental integer identifiers and are handled in FIFO order.
*
* Note: This implementation is not persistent and should not be used in production, as all data is lost when the
* process ends.
*/
final class InMemoryAdapter implements AdapterInterface
{
/**
* @var MessageInterface[]
* @psalm-var array<int, MessageInterface>
*/
private array $messages = [];
private int $current = 0;
/**
* @return MessageInterface[]
* @psalm-return list<MessageInterface>
*/
public function getMessagesList(): array
{
return array_values($this->messages);
}
public function push(MessageInterface $message): MessageInterface
{
$id = count($this->messages) + $this->current;
$this->messages[] = $message;
return new IdEnvelope($message, $id);
}
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 subscribe(callable $handlerCallback): void
{
$this->runExisting($handlerCallback);
}
public function status(int|string $id): MessageStatus
{
$id = (int) $id;
if ($id < 0) {
return MessageStatus::NOT_FOUND;
}
if ($id < $this->current) {
return MessageStatus::DONE;
}
if (isset($this->messages[$id])) {
return MessageStatus::WAITING;
}
return MessageStatus::NOT_FOUND;
}
public function hasStatusSupport(): bool
{
return true;
}
}