Completed
Push — master ( 05aed6...998c1c )
by Jesse
05:22
created

CanBeNull   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 13
dl 0
loc 49
rs 10
c 0
b 0
f 0

6 Methods

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