1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Enjoys\Forms\Rule; |
6
|
|
|
|
7
|
|
|
use Enjoys\Forms\Element; |
8
|
|
|
use Enjoys\Forms\Interfaces\Ruleable; |
9
|
|
|
use Enjoys\Forms\Rules; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @example |
13
|
|
|
* new Equal($message, ['expect']); or |
14
|
|
|
* new Equal($message, (array) 'expect'); or |
15
|
|
|
* new Equal($message, ['expect', 1, '255']); |
16
|
|
|
*/ |
17
|
|
|
class Equal extends Rules implements RuleInterface |
18
|
|
|
{ |
19
|
13 |
|
public function setMessage(?string $message = null): ?string |
20
|
|
|
{ |
21
|
13 |
|
if (is_null($message)) { |
22
|
13 |
|
$message = 'Допустимые значения (указаны через запятую): ' . \implode(', ', $this->getParams()); |
23
|
|
|
} |
24
|
13 |
|
return parent::setMessage($message); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @psalm-suppress PossiblyNullReference |
29
|
|
|
* @param Ruleable&Element $element |
30
|
|
|
* @return bool |
31
|
|
|
*/ |
32
|
13 |
|
public function validate(Ruleable $element): bool |
33
|
|
|
{ |
34
|
|
|
|
35
|
13 |
|
$method = $this->getRequest()->getRequest()->getMethod(); |
36
|
13 |
|
$requestData = match (strtolower($method)) { |
37
|
13 |
|
'get' => $this->getRequest()->getQueryData()->toArray(), |
38
|
|
|
'post' => $this->getRequest()->getPostData()->toArray(), |
39
|
|
|
default => [] |
40
|
|
|
}; |
41
|
13 |
|
$value = \getValueByIndexPath($element->getName(), $requestData); |
|
|
|
|
42
|
|
|
|
43
|
13 |
|
if (false === $this->check($value)) { |
44
|
5 |
|
$element->setRuleError($this->getMessage()); |
45
|
5 |
|
return false; |
46
|
|
|
} |
47
|
|
|
|
48
|
8 |
|
return true; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
|
52
|
13 |
|
private function check($value) |
53
|
|
|
{ |
54
|
|
|
|
55
|
13 |
|
if ($value === false) { |
56
|
1 |
|
return true; |
57
|
|
|
} |
58
|
12 |
|
if (is_array($value)) { |
59
|
4 |
|
foreach ($value as $_val) { |
60
|
4 |
|
if (false === $this->check($_val)) { |
61
|
1 |
|
return false; |
62
|
|
|
} |
63
|
|
|
} |
64
|
3 |
|
return true; |
65
|
|
|
} |
66
|
|
|
|
67
|
12 |
|
return array_search($value, $this->getParams()); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|