1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace FigTree\Validation; |
4
|
|
|
|
5
|
|
|
use FigTree\Exceptions\UnexpectedTypeException; |
6
|
|
|
use FigTree\Validation\Contracts\{ |
7
|
|
|
FilterFactoryInterface, |
8
|
|
|
FilterInterface, |
9
|
|
|
RuleFactoryInterface, |
10
|
|
|
RuleInterface, |
11
|
|
|
}; |
12
|
|
|
|
13
|
|
|
class FilterFactory implements FilterFactoryInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Construct an instance of FilterFactory. |
17
|
|
|
*/ |
18
|
|
|
public function __construct(protected RuleFactoryInterface $ruleFactory) |
19
|
|
|
{ |
20
|
|
|
// |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Get the assigned RuleFactory instance. |
25
|
|
|
* |
26
|
|
|
* @return \FigTree\Validation\Contracts\RuleFactoryInterface |
27
|
|
|
*/ |
28
|
|
|
public function getRuleFactory(): RuleFactoryInterface |
29
|
|
|
{ |
30
|
|
|
return $this->ruleFactory; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Create a Filter using Rules. |
35
|
|
|
* |
36
|
|
|
* @param callable Callback function taking a RuleFactoryInterface and returning an associative array of Rules. |
37
|
|
|
* |
38
|
|
|
* @return \FigTree\Validation\Contracts\FilterInterface |
39
|
|
|
*/ |
40
|
|
|
public function create(callable $callback): FilterInterface |
41
|
|
|
{ |
42
|
|
|
$rules = $this->createRules($callback); |
43
|
|
|
|
44
|
|
|
$filter = new Filter($rules); |
45
|
|
|
|
46
|
|
|
$filter->setRuleFactory($this->ruleFactory); |
47
|
|
|
|
48
|
|
|
return $filter; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Run the creation callback method and validate its results. |
53
|
|
|
* |
54
|
|
|
* @param callable Callback function taking a RuleFactoryInterface and returning an associative array of Rules. |
55
|
|
|
* |
56
|
|
|
* @return array |
57
|
|
|
*/ |
58
|
|
|
protected function createRules(callable $callback): array |
59
|
|
|
{ |
60
|
|
|
$rules = $callback($this->ruleFactory); |
61
|
|
|
|
62
|
|
|
if (!is_array($rules)) { |
63
|
|
|
throw new UnexpectedTypeException($rules, 'array'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
if (array_is_list($rules)) { |
67
|
|
|
throw new UnexpectedTypeException($rules, 'associative array'); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
array_walk($rules, function ($rule) { |
71
|
|
|
if (!($rule instanceof RuleInterface)) { |
72
|
|
|
throw new UnexpectedTypeException($rule, RuleInterface::class); |
73
|
|
|
} |
74
|
|
|
}); |
75
|
|
|
|
76
|
|
|
return $rules; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|