1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\Hydration\Mapping\Property\Scalar; |
5
|
|
|
|
6
|
|
|
use function array_key_exists; |
7
|
|
|
use Stratadox\Hydration\Mapping\Property\MissingTheKey; |
8
|
|
|
use Stratadox\Hydration\Mapping\Property\UnmappableProperty; |
9
|
|
|
use Stratadox\HydrationMapping\ExposesDataKey; |
10
|
|
|
use Stratadox\HydrationMapping\UnmappableInput; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Decorates scalar type declaration with a possibly integer property. |
14
|
|
|
* |
15
|
|
|
* @package Stratadox\Hydrate |
16
|
|
|
* @author Stratadox |
17
|
|
|
*/ |
18
|
|
|
final class CanBeInteger 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 possibly integer type wrapper. |
29
|
|
|
* |
30
|
|
|
* @param ExposesDataKey $mapping The mapping to decorate. |
31
|
|
|
* @return self The possibly integer mapping. |
32
|
|
|
*/ |
33
|
|
|
public static function or(ExposesDataKey $mapping): self |
34
|
|
|
{ |
35
|
|
|
return new self($mapping); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** @inheritdoc */ |
39
|
|
|
public function value(array $data, $owner = null) |
40
|
|
|
{ |
41
|
|
|
$value = $this->my($data); |
42
|
|
|
if ($this->looksLikeAnInteger($value)) { |
43
|
|
|
return (int) $value; |
44
|
|
|
} |
45
|
|
|
try { |
46
|
|
|
return $this->or->value($data, $owner); |
47
|
|
|
} catch (UnmappableInput $exception) { |
48
|
|
|
throw UnmappableProperty::addAlternativeTypeInformation( |
49
|
|
|
'integer', |
50
|
|
|
$exception |
51
|
|
|
); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** @inheritdoc */ |
56
|
|
|
public function name(): string |
57
|
|
|
{ |
58
|
|
|
return $this->or->name(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** @inheritdoc */ |
62
|
|
|
public function key(): string |
63
|
|
|
{ |
64
|
|
|
return $this->or->key(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** @throws UnmappableInput */ |
68
|
|
|
private function my(array $data) |
69
|
|
|
{ |
70
|
|
|
$key = $this->or->key(); |
71
|
|
|
if (array_key_exists($key, $data)) { |
72
|
|
|
return $data[$key]; |
73
|
|
|
} |
74
|
|
|
throw MissingTheKey::inTheInput($data, $this, $key); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
private function looksLikeAnInteger($value): bool |
78
|
|
|
{ |
79
|
|
|
if (!preg_match('/^[-+]?\d+$/', (string) $value)) { |
80
|
|
|
return false; |
81
|
|
|
} |
82
|
|
|
if ($value > PHP_INT_MAX || $value < PHP_INT_MIN) { |
83
|
|
|
return false; |
84
|
|
|
} |
85
|
|
|
return true; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|