JSONDomainEventFactory::create()   B
last analyzed

Complexity

Conditions 9
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.0555
c 0
b 0
f 0
cc 9
nc 4
nop 1
1
<?php
2
3
namespace Cmp\Queues\Domain\Event;
4
5
use Cmp\Queues\Domain\Event\Exception\DomainEventException;
6
use Cmp\Queues\Domain\Event\Exception\InvalidJSONDomainEventException;
7
use Cmp\Queues\Domain\Queue\JSONMessageFactory;
8
9
class JSONDomainEventFactory implements JSONMessageFactory
10
{
11
    /**
12
     * @param string $json
13
     *
14
     * @return DomainEvent
15
     * @throws InvalidJSONDomainEventException
16
     */
17
    public function create($json)
18
    {
19
        $domainEventArray = json_decode($json, true);
20
21
        if (json_last_error() !== JSON_ERROR_NONE) {
22
            throw new InvalidJSONDomainEventException("String is not valid JSON");
23
        }
24
25
        if (!isset($domainEventArray['origin'], $domainEventArray['name'], $domainEventArray['version'], $domainEventArray['occurredOn'])) {
26
            throw new InvalidJSONDomainEventException("Cannot reconstruct domain event. Origin, name, version, occurredOn or body fields are missing");
27
        }
28
29
        try {
30
            return new DomainEvent(
31
                $domainEventArray['origin'],
32
                $domainEventArray['name'],
33
                $domainEventArray['version'],
34
                $domainEventArray['occurredOn'],
35
                isset($domainEventArray['body']) ? $domainEventArray['body'] : [],
36
                isset($domainEventArray['id']) ? $domainEventArray['id'] : null,
37
                isset($domainEventArray['isDeprecated']) ? $domainEventArray['isDeprecated'] : false,
38
                isset($domainEventArray['correlationId']) ? $domainEventArray['correlationId'] : null,
39
                isset($domainEventArray['context']) ? $domainEventArray['context'] : ""
40
            );
41
        } catch (DomainEventException $e) {
42
            throw new InvalidJSONDomainEventException("Failed creating DomainEvent instance", 0, $e);
43
        }
44
    }
45
}
46