Passed
Push — master ( dd3a40...b9ffdf )
by Hirofumi
07:38
created

InMemoryNotificationRepository::notificationOfId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Shippinno\Notification\Infrastructure\Domain\Model;
5
6
use Shippinno\Notification\Domain\Model\DeduplicationKey;
7
use Shippinno\Notification\Domain\Model\Notification;
8
use Shippinno\Notification\Domain\Model\NotificationId;
9
use Shippinno\Notification\Domain\Model\NotificationRepository;
10
11
class InMemoryNotificationRepository implements NotificationRepository
12
{
13
    /**
14
     * @var Notification[]
15
     */
16
    private $notifications = [];
17
18
    private $nextIdentity = 1;
19
20
    /**
21
     * {@inheritdoc}
22
     */
23 1
    public function add(Notification $notification): void
24
    {
25 1
        $deduplicationKey = $notification->deduplicationKey();
26 1
        if (!is_null($deduplicationKey) && $this->hasNotificationOfDeduplicationKey($deduplicationKey)) {
27
            return;
28
        }
29 1
        $this->notifications[$this->nextIdentity()->id()] = $notification;
30 1
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35 2
    public function notificationOfId(NotificationId $notificationId): ?Notification
36
    {
37 2
        if (!isset($this->notifications[$notificationId->id()])) {
38 1
            return null;
39
        }
40
41 1
        return $this->notifications[$notificationId->id()];
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function hasNotificationOfDeduplicationKey(DeduplicationKey $deduplicationKey): bool
48
    {
49
        foreach ($this->notifications as $notification) {
50
            if ($notification->deduplicationKey()->equals($deduplicationKey)) {
51
                return true;
52
            }
53
        }
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function unsentNotifications(): array
60
    {
61
        return array_filter($this->notifications, function (Notification $notification) {
62
            return !$notification->isSent();
63
        });
64
    }
65
66
    /**
67
     * @return NotificationId
68
     */
69 1
    private function nextIdentity(): NotificationId
70
    {
71 1
        return new NotificationId($this->nextIdentity++);
72
    }
73
}
74