|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Stratadox\Hydration\Mapping\Property\Scalar; |
|
6
|
|
|
|
|
7
|
|
|
use Stratadox\Hydration\Mapping\Property\MissingTheKey; |
|
8
|
|
|
use Stratadox\HydrationMapping\ExposesDataKey; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Maps the data from a single key to a scalar object property. |
|
12
|
|
|
* |
|
13
|
|
|
* @package Stratadox\Hydrate |
|
14
|
|
|
* @author Stratadox |
|
15
|
|
|
*/ |
|
16
|
|
|
abstract class Scalar implements ExposesDataKey |
|
17
|
|
|
{ |
|
18
|
|
|
private $name; |
|
19
|
|
|
private $key; |
|
20
|
|
|
|
|
21
|
|
|
private function __construct(string $name, string $dataKey) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->name = $name; |
|
24
|
|
|
$this->key = $dataKey; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Create a new mapping for the called-upon scalar type object property. |
|
29
|
|
|
* |
|
30
|
|
|
* @param string $name The name of both the key and the property. |
|
31
|
|
|
* @return static|self The concrete scalar mapping object. |
|
32
|
|
|
*/ |
|
33
|
|
|
public static function inProperty(string $name) : self |
|
34
|
|
|
{ |
|
35
|
|
|
return new static($name, $name); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Create a new mapping for the called-upon scalar type object property, |
|
40
|
|
|
* using the data from a specific key. |
|
41
|
|
|
* |
|
42
|
|
|
* @param string $name The name of the property. |
|
43
|
|
|
* @param string $key The array key to use. |
|
44
|
|
|
* @return static|self |
|
45
|
|
|
*/ |
|
46
|
|
|
public static function inPropertyWithDifferentKey( |
|
47
|
|
|
string $name, string $key |
|
48
|
|
|
) : self |
|
49
|
|
|
{ |
|
50
|
|
|
return new static($name, $key); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function name() : string |
|
54
|
|
|
{ |
|
55
|
|
|
return $this->name; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function key() : string |
|
59
|
|
|
{ |
|
60
|
|
|
return $this->key; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* Retrieve the data that is relevant for this mapping. |
|
65
|
|
|
* |
|
66
|
|
|
* @param array $data The input data. |
|
67
|
|
|
* @return mixed The value for our key in the input array. |
|
68
|
|
|
*/ |
|
69
|
|
|
protected function my(array $data) |
|
70
|
|
|
{ |
|
71
|
|
|
if (!array_key_exists($this->key(), $data)) { |
|
72
|
|
|
throw MissingTheKey::inTheInput($data, $this, $this->key()); |
|
73
|
|
|
} |
|
74
|
|
|
return $data[$this->key()]; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|