PHPStorage::retrieveMessagesAfterId()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace BenTools\MercurePHP\Storage\PHP;
4
5
use BenTools\MercurePHP\Security\TopicMatcher;
6
use BenTools\MercurePHP\Storage\StorageInterface;
7
use BenTools\MercurePHP\Model\Message;
8
use React\Promise\PromiseInterface;
9
10
use function React\Promise\resolve;
11
12
final class PHPStorage implements StorageInterface
13
{
14
    private int $size;
15
    private int $currentSize = 0;
16
17
    /**
18
     * @var array
19
     */
20
    private array $messages = [];
21
22 5
    public function __construct(int $size)
23
    {
24 5
        $this->size = $size;
25 5
    }
26
27 1
    public function retrieveMessagesAfterId(string $id, array $subscribedTopics): PromiseInterface
28
    {
29 1
        if (self::EARLIEST === $id) {
30 1
            return resolve($this->getAllMessages($subscribedTopics));
31
        }
32
33 1
        return resolve($this->getMessagesAfterId($id, $subscribedTopics));
34
    }
35
36 4
    public function storeMessage(string $topic, Message $message): PromiseInterface
37
    {
38 4
        if (0 === $this->size) {
39 1
            return resolve(true);
40
        }
41
42 3
        if ($this->currentSize >= $this->size) {
43 1
            \array_shift($this->messages);
44
        }
45 3
        $this->messages[] = [$topic, $message];
46 3
        $this->currentSize++;
47
48 3
        return resolve(true);
49
    }
50
51 1
    private function getMessagesAfterId(string $id, array $subscribedTopics): iterable
52
    {
53 1
        $ignore = true;
54 1
        foreach ($this->messages as [$topic, $message]) {
55 1
            if ($message->getId() === $id) {
56 1
                $ignore = false;
57 1
                continue;
58
            }
59 1
            if ($ignore || !TopicMatcher::matchesTopicSelectors($topic, $subscribedTopics)) {
60 1
                continue;
61
            }
62 1
            yield $topic => $message;
63
        }
64 1
    }
65
66 1
    private function getAllMessages(array $subscribedTopics): iterable
67
    {
68 1
        foreach ($this->messages as [$topic, $message]) {
69 1
            if (!TopicMatcher::matchesTopicSelectors($topic, $subscribedTopics)) {
70 1
                continue;
71
            }
72 1
            yield $topic => $message;
73
        }
74 1
    }
75
}
76