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\Traits\Request; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Description of Required |
13
|
|
|
* |
14
|
|
|
* $form->text($name, $title)->addRule('required'); |
15
|
|
|
* $form->text($name, $title)->addRule('required', $message); |
16
|
|
|
* |
17
|
|
|
*/ |
18
|
|
|
class Required implements RuleInterface |
19
|
|
|
{ |
20
|
|
|
use Request; |
21
|
|
|
|
22
|
|
|
private ?string $message; |
23
|
|
|
|
24
|
3 |
|
public function __construct(?string $message = null) |
25
|
|
|
{ |
26
|
3 |
|
$this->message = $message ?? 'Обязательно для заполнения, или выбора'; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @psalm-suppress PossiblyNullReference |
32
|
|
|
* @param Ruleable&Element $element |
33
|
|
|
* @return bool |
34
|
|
|
*/ |
35
|
2 |
|
public function validate(Ruleable $element): bool |
36
|
|
|
{ |
37
|
|
|
/** @var array $requestData */ |
38
|
2 |
|
$requestData = match (strtolower($this->getRequest()->getMethod())) { |
39
|
2 |
|
'get' => $this->getRequest()->getQueryParams(), |
40
|
2 |
|
'post' => $this->getRequest()->getParsedBody(), |
41
|
2 |
|
default => [] |
42
|
2 |
|
}; |
43
|
2 |
|
$_value = \getValueByIndexPath($element->getName(), $requestData); |
|
|
|
|
44
|
2 |
|
if (!$this->check($_value)) { |
45
|
1 |
|
$element->setRuleError($this->message); |
46
|
1 |
|
return false; |
47
|
|
|
} |
48
|
1 |
|
return true; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param mixed $value |
54
|
|
|
* @return bool |
55
|
|
|
*/ |
56
|
2 |
|
private function check(mixed $value): bool |
57
|
|
|
{ |
58
|
2 |
|
if (is_array($value)) { |
59
|
|
|
return count($value) > 0; |
60
|
|
|
} |
61
|
2 |
|
return \trim((string) $value) != ''; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|