Completed
Push — master ( 0d47c0...ecf131 )
by Jesse
05:02
created

HasOneNested::mustHaveTheKeyInThe()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydration\Mapping\Property\Relationship;
5
6
use Stratadox\HydrationMapping\ExposesDataKey;
7
use Stratadox\Hydrator\Hydrates;
8
use Throwable;
9
10
/**
11
 * Maps a nested data structure to a has-one relation in an object property.
12
 *
13
 * @package Stratadox\Hydrate
14
 * @author Stratadox
15
 */
16
final class HasOneNested implements ExposesDataKey
17
{
18
    use KeyRequiring;
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
     * Creates 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
        return new self($name, $name, $hydrator);
43
    }
44
45
    /**
46
     * Creates a new nested has-one mapping, using the data from a specific key.
47
     *
48
     * @param string   $name     The name of the property.
49
     * @param string   $key      The name of the key.
50
     * @param Hydrates $hydrator The hydrator for the nested object.
51
     * @return self              The nested has-one mapping.
52
     */
53
    public static function inPropertyWithDifferentKey(
54
        string $name,
55
        string $key,
56
        Hydrates $hydrator
57
    ): self {
58
        return new self($name, $key, $hydrator);
59
    }
60
61
    /** @inheritdoc */
62
    public function name() : string
63
    {
64
        return $this->name;
65
    }
66
67
    /** @inheritdoc */
68
    public function key() : string
69
    {
70
        return $this->key;
71
    }
72
73
    /** @inheritdoc */
74
    public function value(array $data, $owner = null)
75
    {
76
        $this->mustHaveTheKeyInThe($data);
77
        try {
78
            return $this->hydrate->fromArray($data[$this->key()]);
79
        } catch (Throwable $exception) {
80
            throw ObjectMappingFailed::tryingToMapItem($this, $exception);
81
        }
82
    }
83
}
84