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

TypeValidatingEventSerializer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A unserializePayload() 0 10 2
A __construct() 0 6 1
A serializeEvent() 0 10 2
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