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
|
|
|
return new self($name, $name, $hydrator); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Create 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
|
|
|
public function name() : string |
62
|
|
|
{ |
63
|
|
|
return $this->name; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function key() : string |
67
|
|
|
{ |
68
|
|
|
return $this->key; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function value(array $data, $owner = null) |
72
|
|
|
{ |
73
|
|
|
$this->mustHaveTheKeyInThe($data); |
74
|
|
|
try { |
75
|
|
|
return $this->hydrate->fromArray($data[$this->key()]); |
76
|
|
|
} catch (Throwable $exception) { |
77
|
|
|
throw ObjectMappingFailed::tryingToMapItem($this, $exception); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
private function mustHaveTheKeyInThe(array $data): void |
82
|
|
|
{ |
83
|
|
|
if (!array_key_exists($this->key(), $data)) { |
84
|
|
|
throw MissingTheKey::inTheInput($data, $this, $this->key()); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|