-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPayloadFromReflection.php
More file actions
85 lines (72 loc) · 2.39 KB
/
Copy pathPayloadFromReflection.php
File metadata and controls
85 lines (72 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php declare(strict_types=1);
namespace Star\Component\DomainEvent\Serialization;
use InvalidArgumentException;
use ReflectionClass;
use Star\Component\DomainEvent\DomainEvent;
use Star\Component\DomainEvent\Serialization\Transformation\PropertyValueTransformer;
use Star\Component\DomainEvent\Serialization\Transformation\SerializableAttributeTransformer;
use function get_class;
use function is_bool;
use function is_scalar;
use function is_subclass_of;
use function sprintf;
final class PayloadFromReflection implements PayloadSerializer
{
/**
* @var array<int, PropertyValueTransformer>
*/
private array $transformers;
public function __construct()
{
$this->transformers = [
new SerializableAttributeTransformer(), // for BC
];
}
public function registerTransformer(
PropertyValueTransformer $transformer
): void {
$this->transformers[] = $transformer;
}
public function createPayload(
DomainEvent $event,
): Payload {
$reflection = new ReflectionClass($event);
$properties = $reflection->getProperties();
$payload = [
'event_class' => get_class($event),
];
foreach ($properties as $property) {
$property->setAccessible(true);
$value = $property->getValue($event);
$attribute = $property->getName();
foreach ($this->transformers as $transformer) {
$value = $transformer->eventPropertyToPayloadValue($attribute, $value);
}
if (! is_bool($value) && ! is_scalar($value)) {
throw new NotSupportedTypeInPayload($attribute, $value);
}
$payload[$attribute] = $value;
}
return Payload::fromArray($payload);
}
public function createEvent(
string $eventName,
Payload $payload,
): DomainEvent {
if (is_subclass_of($eventName, CreatedFromPayload::class)) {
return $eventName::fromPayload($payload);
}
throw new InvalidArgumentException(
sprintf(
'Event with name "%s" must implement interface "%s" in order to be re-created.',
$eventName,
CreatedFromPayload::class,
)
);
}
public function createEventName(
DomainEvent $event,
): string {
return get_class($event);
}
}