JsonTransform   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 47
rs 10
c 1
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A value() 0 4 1
A fromKey() 0 3 1
A name() 0 3 1
A __construct() 0 4 1
A decode() 0 17 3
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