Passed
Push — master ( 47d367...c6d1df )
by Hirofumi
06:59
created

InMemoryNotificationRepository::setNotification()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
ccs 0
cts 1
cp 0
cc 1
nc 1
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
    /**
19
     * @var int
20
     */
21
    private $nextIdentity = 1;
22
23
    /**
24
     * {@inheritdoc}
25
     */
26 2
    public function add(Notification $notification): void
27
    {
28 2
        $deduplicationKey = $notification->deduplicationKey();
29 2
        if (!is_null($deduplicationKey) && $this->hasNotificationOfDeduplicationKey($deduplicationKey)) {
30
            return;
31
        }
32 2
        $notification->setNotificationId($this->nextIdentity());
33 2
        $this->persist($notification);
34 2
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 2
    public function persist(Notification $notification): void
40
    {
41 2
        $this->notifications[$notification->notificationId()->id()] = $notification;
42 2
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 3
    public function notificationOfId(NotificationId $notificationId): ?Notification
48
    {
49 3
        if (!isset($this->notifications[$notificationId->id()])) {
50 1
            return null;
51
        }
52
53 2
        return clone $this->notifications[$notificationId->id()];
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function hasNotificationOfDeduplicationKey(DeduplicationKey $deduplicationKey): bool
60
    {
61
        foreach ($this->notifications as $notification) {
62
            if ($notification->deduplicationKey()->equals($deduplicationKey)) {
63
                return true;
64
            }
65
        }
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 1
    public function freshNotifications(): array
72
    {
73 1
        $unsent = [];
74 1
        foreach ($this->notifications as $notification) {
75 1
            if ($notification->isFresh()) {
76 1
                $unsent[] = clone $notification;
77
            }
78
        }
79
80 1
        return $unsent;
81
    }
82
83
    /**
84
     * @return NotificationId
85
     */
86 2
    private function nextIdentity(): NotificationId
87
    {
88 2
        return new NotificationId($this->nextIdentity++);
89
    }
90
}
91