Enjoyzz /
forms
| 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 | 17 | public function __construct(?string $message = null) |
|
| 25 | { |
||
| 26 | 17 | $this->message = $message ?? 'Обязательно для заполнения, или выбора'; |
|
| 27 | } |
||
| 28 | |||
| 29 | |||
| 30 | /** |
||
| 31 | * @psalm-suppress PossiblyNullReference |
||
| 32 | * @param Ruleable&Element $element |
||
| 33 | * @return bool |
||
| 34 | */ |
||
| 35 | 10 | public function validate(Ruleable $element): bool |
|
| 36 | { |
||
| 37 | /** @var array $requestData */ |
||
| 38 | 10 | $requestData = match (strtolower($this->getRequest()->getMethod())) { |
|
| 39 | 10 | 'get' => $this->getRequest()->getQueryParams(), |
|
| 40 | 10 | 'post' => $this->getRequest()->getParsedBody(), |
|
| 41 | 10 | default => [] |
|
| 42 | 10 | }; |
|
| 43 | 10 | $_value = \getValueByIndexPath($element->getName(), $requestData); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 44 | 10 | if (!$this->check($_value)) { |
|
| 45 | 6 | $element->setRuleError($this->message); |
|
| 46 | 6 | return false; |
|
| 47 | } |
||
| 48 | 6 | return true; |
|
| 49 | } |
||
| 50 | |||
| 51 | |||
| 52 | /** |
||
| 53 | * @param mixed $value |
||
| 54 | * @return bool |
||
| 55 | */ |
||
| 56 | 14 | private function check(mixed $value): bool |
|
| 57 | { |
||
| 58 | 14 | if (is_array($value)) { |
|
| 59 | 3 | return count($value) > 0; |
|
| 60 | } |
||
| 61 | 11 | return \trim((string) $value) != ''; |
|
| 62 | } |
||
| 63 | } |
||
| 64 |