JsonTransform::decode()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
nc 3
nop 1
dl 0
loc 17
rs 9.8666
c 1
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Hydration\Mapping\Transform;
4
5
use Stratadox\Hydration\Mapping\AssertKey;
6
use Stratadox\HydrationMapping\Mapping;
7
use Stratadox\HydrationMapping\MappingFailure;
8
use function gettype;
9
use function is_array;
10
use function json_decode;
11
use function json_last_error;
12
use function json_last_error_msg;
13
use const JSON_ERROR_NONE;
14
15
final class JsonTransform implements Mapping
16
{
17
    /** @var string */
18
    private $key;
19
    /** @var Mapping */
20
    private $mapping;
21
22
    private function __construct(string $key, Mapping $mapping)
23
    {
24
        $this->key = $key;
25
        $this->mapping = $mapping;
26
    }
27
28
    public static function fromKey(string $key, Mapping $mapping): Mapping
29
    {
30
        return new self($key, $mapping);
31
    }
32
33
    public function name(): string
34
    {
35
        return $this->mapping->name();
36
    }
37
38
    public function value(array $data, $owner = null)
39
    {
40
        AssertKey::exists($this, $data, $this->key);
41
        return $this->mapping->value($this->decode($data[$this->key]), $owner);
42
    }
43
44
    /** @throws MappingFailure */
45
    private function decode(string $json): array
46
    {
47
        $value = json_decode($json, true);
48
        if (is_array($value)) {
49
            return $value;
50
        }
51
        if (json_last_error() !== JSON_ERROR_NONE) {
52
            throw JsonTransformationFailure::detected(
53
                json_last_error_msg(),
54
                $this->key,
55
                $this->name()
56
            );
57
        }
58
        throw JsonTransformationFailure::cannotBeScalar(
59
            gettype($value),
60
            $this->key,
61
            $this->name()
62
        );
63
    }
64
}
65