TypeValidatingPayloadSerializer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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