Passed
Push — master ( cd99cc...e0b963 )
by Jesse
02:16
created

CanBeNull::value()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydration\Mapping\Property\Scalar;
5
6
use function is_null;
7
use Stratadox\Hydration\Mapping\Property\MissingTheKey;
8
use Stratadox\HydrationMapping\ExposesDataKey;
9
use Stratadox\HydrationMapping\UnmappableInput;
10
11
/**
12
 * Decorates scalar type declaration with a nullable property.
13
 *
14
 * @package Stratadox\Hydrate
15
 * @author  Stratadox
16
 */
17
final class CanBeNull implements ExposesDataKey
18
{
19
    private $or;
20
21
    private function __construct(ExposesDataKey $mapping)
22
    {
23
        $this->or = $mapping;
24
    }
25
26
    /**
27
     * Creates a new nullable type wrapper.
28
     *
29
     * @param ExposesDataKey $mapping    The mapping to decorate.
30
     * @return self                      The nullable mapping.
31
     */
32
    public static function or(ExposesDataKey $mapping): self
33
    {
34
        return new self($mapping);
35
    }
36
37
    /** @inheritdoc */
38
    public function value(array $data, $owner = null)
39
    {
40
        if (is_null($this->my($data))) {
41
            return null;
42
        }
43
        return $this->or->value($data, $owner);
44
    }
45
46
    /** @inheritdoc */
47
    public function name(): string
48
    {
49
        return $this->or->name();
50
    }
51
52
    /** @inheritdoc */
53
    public function key(): string
54
    {
55
        return $this->or->key();
56
    }
57
58
    /** @throws UnmappableInput */
59
    private function my(array $data)
60
    {
61
        $key = $this->or->key();
62
        if (array_key_exists($key, $data)) {
63
            return $data[$key];
64
        }
65
        throw MissingTheKey::inTheInput($data, $this, $key);
66
    }
67
}
68