Completed
Push — master ( 2e6a80...fd89d4 )
by Alex
02:25
created

JSONTaskFactory::create()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace Cmp\Queues\Domain\Task;
4
5
use Cmp\Queues\Domain\Queue\JSONMessageFactory;
6
use Cmp\Queues\Domain\Task\Exception\InvalidJSONTaskException;
7
use Cmp\Queues\Domain\Task\Exception\TaskException;
8
9
class JSONTaskFactory implements JSONMessageFactory
10
{
11
    /**
12
     * @param string $json
13
     *
14
     * @return Task
15
     * @throws InvalidJSONTaskException
16
     */
17
    public function create($json)
18
    {
19
        $taskArray = json_decode($json, true);
20
21
        if (json_last_error() !== JSON_ERROR_NONE) {
22
            throw new InvalidJSONTaskException("String is not valid JSON");
23
        }
24
25
        if (!isset($taskArray['name'], $taskArray['body'])) {
26
            throw new InvalidJSONTaskException("Cannot reconstruct task. Name or body fields are missing");
27
        }
28
29
        try {
30
            return new Task($taskArray['name'], $taskArray['body'], isset($taskArray['delay']) ? $taskArray['delay'] : 0);
31
        } catch (TaskException $e) {
32
            throw new InvalidJSONTaskException("Failed creating Task instance", 0, $e);
33
        }
34
    }
35
}
36