Passed
Pull Request — master (#54)
by Frank
01:53
created

TypeValidatingPayloadSerializer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 35
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A unserializePayload() 0 10 2
A serializePayload() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing\Serialization;
6
7
final class TypeValidatingPayloadSerializer implements PayloadSerializer
8
{
9
    private $serializer;
10
    private $eventClassName;
11
12
    public function __construct(
13
        PayloadSerializer $serializer,
14
        string $eventClassName
15
    ) {
16
        $this->serializer = $serializer;
17
        $this->eventClassName = $eventClassName;
18
    }
19
20
    public function serializePayload(object $event): array
21
    {
22
        if ( ! $event instanceof $this->eventClassName) {
23
            throw new \InvalidArgumentException(sprintf(
24
                'Cannot serialize event that does not implement "%s".',
25
                $this->eventClassName
26
            ));
27
        }
28
29
        return $this->serializer->serializePayload($event);
30
    }
31
32
    public function unserializePayload(string $className, array $payload): object
33
    {
34
        if ( ! is_subclass_of($className, $this->eventClassName)) {
35
            throw new \InvalidArgumentException(sprintf(
36
                'Cannot unserialize payload into an event that does not implement "%s".',
37
                $this->eventClassName
38
            ));
39
        }
40
41
        return $this->serializer->unserializePayload($className, $payload);
42
    }
43
}
44