Completed
Pull Request — master (#42)
by Gildas
03:19
created

TypeValidatingEventSerializer::serializeEvent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing\Serialization;
6
7
final class TypeValidatingEventSerializer implements EventSerializer
8
{
9
    private $serializer;
10
    private $eventClassName;
11
12 5
    public function __construct(
13
        EventSerializer $serializer,
14
        string $eventClassName
15
    ) {
16 5
        $this->serializer = $serializer;
17 5
        $this->eventClassName = $eventClassName;
18 5
    }
19
20 2
    public function serializeEvent(object $event): array
21
    {
22 2
        if ( ! $event instanceof $this->eventClassName) {
23 1
            throw new \InvalidArgumentException(sprintf(
24 1
                'Cannot serialize event that does not implement "%s".',
25 1
                $this->eventClassName
26
            ));
27
        }
28
29 1
        return $this->serializer->serializeEvent($event);
30
    }
31
32 2
    public function unserializePayload(string $className, array $payload): object
33
    {
34 2
        if ( ! is_subclass_of($className, $this->eventClassName)) {
35 1
            throw new \InvalidArgumentException(sprintf(
36 1
                'Cannot unserialize payload into an event that does not implement "%s".',
37 1
                $this->eventClassName
38
            ));
39
        }
40
41 1
        return $this->serializer->unserializePayload($className, $payload);
42
    }
43
}
44