Passed
Pull Request — master (#54)
by Frank
08:27
created

serializePayload()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 10
rs 10
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