Completed
Pull Request — master (#366)
by Beñat
04:53
created

RedisEventStore::streamOfId()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Kreta package.
5
 *
6
 * (c) Beñat Espiña <[email protected]>
7
 * (c) Gorka Laucirica <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace Kreta\SharedKernel\Infrastructure\Persistence\Redis\EventStore;
16
17
use Kreta\SharedKernel\Domain\Model\AggregateDoesNotExistException;
18
use Kreta\SharedKernel\Domain\Model\DomainEventCollection;
19
use Kreta\SharedKernel\Domain\Model\Identity\BaseId as Id;
20
use Kreta\SharedKernel\Event\EventStore;
21
use Kreta\SharedKernel\Event\EventStream;
22
use Kreta\SharedKernel\Serialization\Serializer;
23
use Predis\Client;
24
25
final class RedisEventStore implements EventStore
26
{
27
    private const REDIS_KEY_PLACEHOLDER = '%sevents: %s';
28
29
    private $predis;
30
    private $serializer;
31
    private $eventType;
32
33
    public function __construct(Client $predis, Serializer $serializer, string $eventType = null)
34
    {
35
        $this->predis = $predis;
36
        $this->serializer = $serializer;
37
        $this->eventType = $eventType;
38
    }
39
40
    public function appendTo(EventStream $stream) : void
41
    {
42
        foreach ($stream->events() as $event) {
43
            $serializedEvent = $this->serializer->serialize(
44
                [
45
                    'type' => get_class($event),
46
                    'data' => $this->serializer->serialize($event),
47
                ]
48
            );
49
50
            $this->predis->rpush($this->redisKey($stream->aggregateRootId()), $serializedEvent);
51
        }
52
    }
53
54
    public function streamOfId(Id $aggregateRootId) : EventStream
55
    {
56
        if (!$this->predis->exists($this->redisKey($aggregateRootId))) {
57
            throw new AggregateDoesNotExistException($aggregateRootId->id());
58
        }
59
60
        $serializedEvents = $this->predis->lrange($this->redisKey($aggregateRootId), 0, -1);
61
62
        $events = new DomainEventCollection();
63
        foreach ($serializedEvents as $serializedEvent) {
64
            $eventData = $this->serializer->deserialize($serializedEvent, 'array');
0 ignored issues
show
Unused Code introduced by
The call to Serializer::deserialize() has too many arguments starting with 'array'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
65
66
            $events->add(
67
                $this->serializer->deserialize(
68
                    $eventData['data'],
69
                    $eventData['type']
0 ignored issues
show
Unused Code introduced by
The call to Serializer::deserialize() has too many arguments starting with $eventData['type'].

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
70
                )
71
            );
72
        }
73
74
        return new EventStream($aggregateRootId, $events);
75
    }
76
77
    private function redisKey(Id $aggregateRootId) : string
78
    {
79
        $name = '';
80
        if ($this->eventType) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->eventType of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
81
            $name = $this->eventType . '-';
82
        }
83
84
        return sprintf(self::REDIS_KEY_PLACEHOLDER, $name, $aggregateRootId->id());
85
    }
86
}
87