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

JSONDomainEventFactory::create()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 25
rs 8.439
c 1
b 0
f 0
cc 5
eloc 16
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'], $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