Passed
Push — master ( d4b74b...f37c5f )
by Jesse
01:55
created

JsonTransform   A

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 is_array;
9
use function json_decode;
10
use function json_last_error;
11
use function json_last_error_msg;
12
use const JSON_ERROR_NONE;
13
14
final class JsonTransform implements Mapping
15
{
16
    /** @var string */
17
    private $key;
18
    /** @var Mapping */
19
    private $mapping;
20
21
    private function __construct(string $key, Mapping $mapping)
22
    {
23
        $this->key = $key;
24
        $this->mapping = $mapping;
25
    }
26
27
    public static function fromKey(string $key, Mapping $mapping): Mapping
28
    {
29
        return new self($key, $mapping);
30
    }
31
32
    public function name(): string
33
    {
34
        return $this->mapping->name();
35
    }
36
37
    public function value(array $data, $owner = null)
38
    {
39
        AssertKey::exists($this, $data, $this->key);
40
        return $this->mapping->value($this->decode($data[$this->key]), $owner);
41
    }
42
43
    /** @throws MappingFailure */
44
    private function decode(string $json): array
45
    {
46
        $value = json_decode($json, true);
47
        if (is_array($value)) {
48
            return $value;
49
        }
50
        if (json_last_error() !== JSON_ERROR_NONE) {
51
            throw JsonTransformationFailure::detected(
52
                json_last_error_msg(),
53
                $this->key,
54
                $this->name()
55
            );
56
        }
57
        throw JsonTransformationFailure::cannotBeScalar(
58
            $value,
59
            $this->key,
60
            $this->name()
61
        );
62
    }
63
}
64