|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace CultuurNet\UDB3\EventSourcing; |
|
4
|
|
|
|
|
5
|
|
|
use Assert\Assertion; |
|
6
|
|
|
use Broadway\Serializer\SerializerInterface; |
|
7
|
|
|
use Broadway\Serializer\SimpleInterfaceSerializer; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Decorates a SimpleInterfaceSerializer, first maps old class names to new |
|
11
|
|
|
* class names. |
|
12
|
|
|
*/ |
|
13
|
|
|
final class PayloadManipulatingSerializer implements SerializerInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var callable[] |
|
17
|
|
|
*/ |
|
18
|
|
|
private $manipulations; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var SimpleInterfaceSerializer |
|
22
|
|
|
*/ |
|
23
|
|
|
private $serializer; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(SimpleInterfaceSerializer $serializer) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->serializer = $serializer; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function serialize($object): array |
|
31
|
|
|
{ |
|
32
|
|
|
return $this->serializer->serialize($object); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function manipulateEventsOfClass(string $className, callable $callback): void |
|
36
|
|
|
{ |
|
37
|
|
|
if (isset($this->manipulations[$className])) { |
|
38
|
|
|
throw new \RuntimeException( |
|
39
|
|
|
"Manipulation on events of class {$className} already added, " . |
|
40
|
|
|
"can add only one." |
|
41
|
|
|
); |
|
42
|
|
|
} |
|
43
|
|
|
$this->manipulations[$className] = $callback; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public function deserialize(array $serializedObject) |
|
47
|
|
|
{ |
|
48
|
|
|
$manipulatedSerializedObject = $this->manipulate($serializedObject); |
|
49
|
|
|
|
|
50
|
|
|
return $this->serializer->deserialize($manipulatedSerializedObject); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
private function manipulate(array $serializedObject): array |
|
54
|
|
|
{ |
|
55
|
|
|
Assertion::keyExists( |
|
56
|
|
|
$serializedObject, |
|
57
|
|
|
'class', |
|
58
|
|
|
"Key 'class' should be set." |
|
59
|
|
|
); |
|
60
|
|
|
|
|
61
|
|
|
$manipulatedSerializedObject = $serializedObject; |
|
62
|
|
|
$class = $manipulatedSerializedObject['class']; |
|
63
|
|
|
|
|
64
|
|
|
if (isset($this->manipulations[$class])) { |
|
65
|
|
|
$manipulatedSerializedObject = $this->manipulations[$class]($manipulatedSerializedObject); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $manipulatedSerializedObject; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|