Completed
Pull Request — master (#17)
by Alex
01:50
created

JSONDomainEventFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 34
rs 10
c 1
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B create() 0 25 5
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'], $domainEventArray['body'])) {
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
                $domainEventArray['body'],
36
                isset($domainEventArray['isDeprecated']) ? $domainEventArray['isDeprecated'] : false
37
            );
38
        } catch (DomainEventException $e) {
39
            throw new InvalidJSONDomainEventException("Failed creating DomainEvent instance", 0, $e);
40
        }
41
    }
42
}
43