Completed
Push — master ( 263533...6dddbe )
by Beñat
01:46
created

StoredEvent::setOccurredOn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Shared Kernel library.
5
 *
6
 * Copyright (c) 2016-present LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace LIN3S\SharedKernel\Event;
15
16
use LIN3S\SharedKernel\Domain\Model\DomainEvent;
17
use LIN3S\SharedKernel\Exception\InvalidArgumentException;
18
19
/**
20
 * @author Beñat Espiña <[email protected]>
21
 */
22
class StoredEvent implements \JsonSerializable
23
{
24
    private $order;
25
    private $type;
26
    private $payload;
27
    private $serializedEvent;
28
    private $occurredOn;
29
    private $streamName;
30
    private $streamVersion;
31
32
    public function __construct(DomainEvent $event, StreamName $name, StreamVersion $version)
33
    {
34
        $this->type = get_class($event);
35
        $this->setOccurredOn($event->occurredOn());
36
        $this->streamName = $name->name();
37
        $this->streamVersion = $version->version();
38
39
        $this->setPayload($event);
40
        $this->setSerializedEvent($event);
41
    }
42
43
    public function jsonSerialize() : array
44
    {
45
        return [
46
            'order'          => $this->order,
47
            'type'           => $this->formatType(),
48
            'occurred_on'    => $this->occurredOn,
49
            'payload'        => $this->serializedEvent,
50
            'stream_name'    => $this->streamName,
51
            'stream_version' => $this->streamVersion,
52
        ];
53
    }
54
55
    public function toArray() : array
56
    {
57
        return [
58
            $this->type,
59
            $this->payload,
60
            $this->occurredOn,
61
            $this->streamName,
62
            $this->streamVersion,
63
        ];
64
    }
65
66
    private function setPayload(DomainEvent $event) : void
67
    {
68
        $this->payload = [];
69
        $eventReflection = new \ReflectionClass($event);
70 View Code Duplication
        foreach ($eventReflection->getProperties() as $property) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
71
            if ('occurredOn' === $property->getName()) {
72
                continue;
73
            }
74
            $property->setAccessible(true);
75
            $this->payload[$property->getName()] = $this->serializePayload($property, $event);
76
        }
77
        $this->payload = json_encode($this->payload);
78
    }
79
80
    private function setSerializedEvent(DomainEvent $event) : void
81
    {
82
        $this->serializedEvent = [];
83
        $eventReflection = new \ReflectionClass($event);
84 View Code Duplication
        foreach ($eventReflection->getProperties() as $property) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
            if ('occurredOn' === $property->getName()) {
86
                continue;
87
            }
88
            $property->setAccessible(true);
89
            $this->serializedEvent[$property->getName()] = $this->serializeEvent($property, $event);
90
        }
91
    }
92
93
    private function setOccurredOn(\DateTimeInterface $occurredOn) : void
94
    {
95
        $this->checkDateTimeIsValid($occurredOn);
96
        $occurredOn->setTimezone(new \DateTimeZone('UTC'));
97
        $this->occurredOn = $occurredOn->getTimestamp();
98
    }
99
100
    private function checkDateTimeIsValid(\DateTimeInterface $occurredOn) : void
101
    {
102
        if (!($occurredOn instanceof \DateTimeImmutable) && !($occurredOn instanceof \DateTime)) {
103
            throw new InvalidArgumentException('Given occurredOn is not a \DateTime or \DateTimeImmutable instance');
104
        }
105
    }
106
107 View Code Duplication
    private function serializePayload(\ReflectionProperty $property, $object, array $result = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
    {
109
        $property->setAccessible(true);
110
        $value = $property->getValue($object);
111
        if (is_scalar($value)) {
112
            return $value;
113
        }
114
115
        $className = get_class($value);
116
        $reflectionClass = new \ReflectionClass($value);
117
        $properties = $reflectionClass->getProperties();
118
119
        foreach ($properties as $property) {
120
            $result[$className][$property->getName()] = $this->serializePayload($property, $value);
121
        }
122
123
        return $result;
124
    }
125
126 View Code Duplication
    private function serializeEvent(\ReflectionProperty $property, $object, array $result = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
127
    {
128
        $property->setAccessible(true);
129
        $value = $property->getValue($object);
130
        if (is_scalar($value)) {
131
            return $value;
132
        }
133
134
        $className = get_class($value);
0 ignored issues
show
Unused Code introduced by
$className is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
135
        $reflectionClass = new \ReflectionClass($value);
136
        $properties = $reflectionClass->getProperties();
137
138
        foreach ($properties as $property) {
139
            $result = $this->serializeEvent($property, $value, $result);
140
        }
141
142
        return $result;
143
    }
144
145
    private function formatType() : string
146
    {
147
        return mb_strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', array_reverse(explode('\\', $this->type))[0]));
148
    }
149
}
150