|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Karma\Formatters; |
|
6
|
|
|
|
|
7
|
|
|
use Karma\Formatter; |
|
8
|
|
|
|
|
9
|
|
|
class Rules implements Formatter |
|
10
|
|
|
{ |
|
11
|
|
|
private array |
|
|
|
|
|
|
12
|
|
|
$rules; |
|
13
|
|
|
|
|
14
|
21 |
|
public function __construct(array $rules) |
|
15
|
|
|
{ |
|
16
|
21 |
|
$this->convertRules($rules); |
|
17
|
21 |
|
} |
|
18
|
|
|
|
|
19
|
21 |
|
private function getSpecialValuesMappingTable(): array |
|
20
|
|
|
{ |
|
21
|
|
|
return [ |
|
22
|
21 |
|
'<true>' => true, |
|
23
|
|
|
'<false>' => false, |
|
24
|
|
|
'<null>' => null, |
|
25
|
21 |
|
'<string>' => function($value) { |
|
26
|
12 |
|
return is_string($value); |
|
27
|
21 |
|
} |
|
28
|
|
|
]; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
21 |
|
private function convertRules(array $rules): void |
|
32
|
|
|
{ |
|
33
|
21 |
|
$this->rules = []; |
|
34
|
21 |
|
$mapping = $this->getSpecialValuesMappingTable(); |
|
35
|
|
|
|
|
36
|
21 |
|
foreach($rules as $value => $result) |
|
37
|
|
|
{ |
|
38
|
21 |
|
$value = trim($value); |
|
39
|
|
|
|
|
40
|
21 |
|
if(is_string($value) && array_key_exists($value, $mapping)) |
|
41
|
|
|
{ |
|
42
|
21 |
|
$result = $this->handleStringFormatting($value, $result); |
|
43
|
21 |
|
$value = $mapping[$value]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
21 |
|
$this->rules[] = [$value, $result]; |
|
47
|
|
|
} |
|
48
|
21 |
|
} |
|
49
|
|
|
|
|
50
|
21 |
|
private function handleStringFormatting(string $value, $result) |
|
51
|
|
|
{ |
|
52
|
21 |
|
if($value === '<string>') |
|
53
|
|
|
{ |
|
54
|
17 |
|
$result = function ($value) use ($result) { |
|
55
|
11 |
|
return str_replace('<string>', $value, $result); |
|
56
|
17 |
|
}; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
21 |
|
return $result; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
19 |
|
public function format($value) |
|
63
|
|
|
{ |
|
64
|
19 |
|
foreach($this->rules as $rule) |
|
65
|
|
|
{ |
|
66
|
19 |
|
list($condition, $result) = $rule; |
|
67
|
|
|
|
|
68
|
19 |
|
if($this->isRuleMatches($condition, $value)) |
|
69
|
|
|
{ |
|
70
|
18 |
|
return $this->applyFormattingRule($result, $value); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
3 |
|
return $value; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
19 |
|
private function isRuleMatches($condition, $value): bool |
|
78
|
|
|
{ |
|
79
|
19 |
|
$hasMatched = ($condition === $value); |
|
80
|
|
|
|
|
81
|
19 |
|
if($condition instanceof \Closure) |
|
82
|
|
|
{ |
|
83
|
12 |
|
$hasMatched = $condition($value); |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
19 |
|
return $hasMatched; |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
18 |
|
private function applyFormattingRule($ruleResult, $value) |
|
90
|
|
|
{ |
|
91
|
18 |
|
if($ruleResult instanceof \Closure) |
|
92
|
|
|
{ |
|
93
|
11 |
|
return $ruleResult($value); |
|
94
|
|
|
} |
|
95
|
|
|
|
|
96
|
7 |
|
return $ruleResult; |
|
97
|
|
|
} |
|
98
|
|
|
} |
|
99
|
|
|
|