1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\Hydration\Mapping\Property\Type; |
5
|
|
|
|
6
|
|
|
use function in_array; |
7
|
|
|
use Stratadox\Hydration\Mapping\Property\UnmappableProperty; |
8
|
|
|
use Stratadox\HydrationMapping\ExposesDataKey; |
9
|
|
|
use Stratadox\HydrationMapping\UnmappableInput; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Decorates @see BooleanValue with custom true/false declarations. |
13
|
|
|
* |
14
|
|
|
* @package Stratadox\Hydrate |
15
|
|
|
* @author Stratadox |
16
|
|
|
*/ |
17
|
|
|
final class CanBeBoolean implements ExposesDataKey |
18
|
|
|
{ |
19
|
|
|
private $or; |
20
|
|
|
private $truths; |
21
|
|
|
private $falsehoods; |
22
|
|
|
|
23
|
|
|
private function __construct( |
24
|
|
|
ExposesDataKey $mapping, |
25
|
|
|
array $truths, |
26
|
|
|
array $falsehoods |
27
|
|
|
) { |
28
|
|
|
$this->or = $mapping; |
29
|
|
|
$this->truths = $truths; |
30
|
|
|
$this->falsehoods = $falsehoods; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Creates a new custom truth mapping, decorating a @see BooleanValue. |
35
|
|
|
* |
36
|
|
|
* @param ExposesDataKey $mapping The mapping to decorate. |
37
|
|
|
* @param array $truths The values to consider true. |
38
|
|
|
* @param array $falsehoods The values to consider false. |
39
|
|
|
* @return ExposesDataKey The custom truth boolean mapping. |
40
|
|
|
*/ |
41
|
|
|
public static function or( |
42
|
|
|
ExposesDataKey $mapping, |
43
|
|
|
array $truths = [true, 1, '1'], |
44
|
|
|
array $falsehoods = [false, 0, '0'] |
45
|
|
|
): ExposesDataKey { |
46
|
|
|
return new self($mapping, $truths, $falsehoods); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** @inheritdoc */ |
50
|
|
|
public function value(array $data, $owner = null) |
51
|
|
|
{ |
52
|
|
|
if (in_array($data[$this->or->key()], $this->truths, true)) { |
53
|
|
|
return true; |
54
|
|
|
} |
55
|
|
|
if (in_array($data[$this->or->key()], $this->falsehoods, true)) { |
56
|
|
|
return false; |
57
|
|
|
} |
58
|
|
|
try { |
59
|
|
|
return $this->or->value($data, $owner); |
60
|
|
|
} catch (UnmappableInput $exception) { |
61
|
|
|
throw UnmappableProperty::addAlternativeTypeInformation( |
62
|
|
|
'boolean', |
63
|
|
|
$exception |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** @inheritdoc */ |
69
|
|
|
public function name(): string |
70
|
|
|
{ |
71
|
|
|
return $this->or->name(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** @inheritdoc */ |
75
|
|
|
public function key(): string |
76
|
|
|
{ |
77
|
|
|
return $this->or->key(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|