Passed
Push — master ( a5d157...2a272c )
by Jesse
04:07
created

HasOneNested::name()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stratadox\Hydration\Mapping\Property\Relationship;
6
7
use Stratadox\Hydration\Mapping\Property\MissingTheKey;
8
use Stratadox\HydrationMapping\ExposesDataKey;
9
use Stratadox\Hydrator\Hydrates;
10
use Throwable;
11
12
/**
13
 * Maps a nested data structure to a has-one relation in an object property.
14
 *
15
 * @package Stratadox\Hydrate
16
 * @author Stratadox
17
 */
18
final class HasOneNested implements ExposesDataKey
19
{
20
    private $name;
21
    private $key;
22
    private $hydrate;
23
24
    private function __construct(string $name, string $dataKey, Hydrates $hydrator)
25
    {
26
        $this->name = $name;
27
        $this->key = $dataKey;
28
        $this->hydrate = $hydrator;
29
    }
30
31
    /**
32
     * Create a new nested has-one mapping.
33
     *
34
     * @param string   $name     The name of the property.
35
     * @param Hydrates $hydrator The hydrator for the nested object.
36
     * @return self              The nested has-one mapping.
37
     */
38
    public static function inProperty(
39
        string $name,
40
        Hydrates $hydrator
41
    ) : self
42
    {
43
        return new self($name, $name, $hydrator);
44
    }
45
46
    /**
47
     * Create a new nested has-one mapping, using the data from a specific key.
48
     *
49
     * @param string   $name     The name of the property.
50
     * @param string   $key      The name of the key.
51
     * @param Hydrates $hydrator The hydrator for the nested object.
52
     * @return self              The nested has-one mapping.
53
     */
54
    public static function inPropertyWithDifferentKey(
55
        string $name,
56
        string $key,
57
        Hydrates $hydrator
58
    ) : self
59
    {
60
        return new self($name, $key, $hydrator);
61
    }
62
63
    public function name() : string
64
    {
65
        return $this->name;
66
    }
67
68
    public function key() : string
69
    {
70
        return $this->key;
71
    }
72
73
    public function value(array $data, $owner = null)
74
    {
75
        if (!array_key_exists($this->key(), $data)) {
76
            throw MissingTheKey::inTheInput($data, $this, $this->key());
77
        }
78
        try {
79
            return $this->hydrate->fromArray($data[$this->key()]);
80
        } catch (Throwable $exception) {
81
            throw ObjectMappingFailed::tryingToMapItem($this, $exception);
82
        }
83
    }
84
}
85