|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Fields\Validation; |
|
4
|
|
|
|
|
5
|
|
|
class ValidationParameters |
|
6
|
|
|
{ |
|
7
|
|
|
/** @var array */ |
|
8
|
|
|
private $rules; |
|
9
|
|
|
|
|
10
|
|
|
/** @var array */ |
|
11
|
|
|
private $customMessages; |
|
12
|
|
|
|
|
13
|
|
|
/** @var array */ |
|
14
|
|
|
private $customAttributes; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct($rules, array $customMessages, array $customAttributes) |
|
17
|
|
|
{ |
|
18
|
|
|
$this->rules = ValidationParameters::normalizeToArray($rules); |
|
19
|
|
|
$this->customMessages = $customMessages; |
|
20
|
|
|
$this->customAttributes = $customAttributes; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
public function getRules(): array |
|
24
|
|
|
{ |
|
25
|
|
|
return $this->rules; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function getMessages(): array |
|
29
|
|
|
{ |
|
30
|
|
|
return $this->customMessages; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function getAttributes(): array |
|
34
|
|
|
{ |
|
35
|
|
|
return $this->customAttributes; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function customizeRules(array $customRules): self |
|
39
|
|
|
{ |
|
40
|
|
|
$rules = $this->rules; |
|
41
|
|
|
|
|
42
|
|
|
foreach ($rules as $k => $rule) { |
|
43
|
|
|
|
|
44
|
|
|
$params = ''; |
|
45
|
|
|
|
|
46
|
|
|
// Split up the rule and any parameters |
|
47
|
|
|
if (false !== strpos($rule, ':')) { |
|
48
|
|
|
list($rule, $params) = explode(':', $rule); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
if (isset($customRules[$rule])) { |
|
52
|
|
|
$rules[$k] = $customRules[$rule] . ($params ? ':' . $params : ''); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return new static($rules, $this->getMessages(), $this->getAttributes()); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/* |
|
60
|
|
|
* Rules can be passed as array of rules or pipe delimited string |
|
61
|
|
|
*/ |
|
62
|
|
|
private static function normalizeToArray($values): array |
|
63
|
|
|
{ |
|
64
|
|
|
if(is_string($values)){ |
|
65
|
|
|
$values = explode('|', $values); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $values; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|