JobFactory::createFromArray()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
nc 4
nop 1
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 4
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace JCIT\jobqueue\factories;
5
6
use InvalidArgumentException;
7
use JCIT\jobqueue\interfaces\JobFactoryInterface;
8
use JCIT\jobqueue\interfaces\JobInterface;
9
10
class JobFactory implements JobFactoryInterface
11
{
12 5
    public function createFromArray(array $data): JobInterface
13
    {
14 5
        if (!isset($data['class'], $data['data'])) {
15 1
            throw new InvalidArgumentException('Data does not contain required class key');
16
        }
17
18 4
        if (!class_exists($data['class'])) {
19 1
            throw new InvalidArgumentException("Unknown class '{$data['class']}' given");
20
        }
21
22 3
        if (!is_subclass_of($data['class'], JobInterface::class)) {
23 1
            throw new InvalidArgumentException("Class '{$data['class']}' does not implement JobInterface");
24
        }
25
26 2
        return $data['class']::fromArray($data['data']);
27
    }
28
29 1
    public function createFromJson(string $data): JobInterface
30
    {
31 1
        return $this->createFromArray(json_decode($data, true));
32
    }
33
34 2
    public function saveToArray(JobInterface $job): array
35
    {
36
        return [
37 2
            'class' => get_class($job),
38 2
            'data' => $job->jsonSerialize(),
39
        ];
40
    }
41
42 1
    public function saveToJson(JobInterface $job): string
43
    {
44 1
        return json_encode($this->saveToArray($job), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
45
    }
46
}
47