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 | class Email implements RuleInterface |
||
12 | { |
||
13 | use Request; |
||
14 | |||
15 | // private $idn_to_ascii = false; |
||
16 | |||
17 | private string $message; |
||
18 | |||
19 | 4 | public function __construct(?string $message = null) |
|
20 | { |
||
21 | 4 | $this->message = $message ?? 'Не правильно введен email'; |
|
22 | } |
||
23 | |||
24 | |||
25 | |||
26 | /** |
||
27 | * @psalm-suppress PossiblyNullReference |
||
28 | * @param Ruleable&Element $element |
||
29 | * @return bool |
||
30 | */ |
||
31 | 3 | public function validate(Ruleable $element): bool |
|
32 | { |
||
33 | 3 | $method = $this->getRequest()->getMethod(); |
|
34 | /** @var array $requestData */ |
||
35 | 3 | $requestData = match (strtolower($method)) { |
|
36 | 3 | 'get' => $this->getRequest()->getQueryParams(), |
|
37 | 3 | 'post' => $this->getRequest()->getParsedBody(), |
|
38 | 3 | default => [] |
|
39 | 3 | }; |
|
40 | /** @var string $value */ |
||
41 | 3 | $value = \getValueByIndexPath($element->getName(), $requestData); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
42 | 3 | if ($this->check(\trim($value)) === false) { |
|
43 | 1 | $element->setRuleError($this->message); |
|
44 | 1 | return false; |
|
45 | } |
||
46 | 2 | return true; |
|
47 | } |
||
48 | |||
49 | |||
50 | 3 | private function check(string $value): bool |
|
51 | { |
||
52 | 3 | if (empty($value)) { |
|
53 | 1 | return true; |
|
54 | } |
||
55 | |||
56 | // if ($this->idn_to_ascii === true) { |
||
57 | // $value = idn_to_ascii($value); |
||
58 | // } |
||
59 | |||
60 | 2 | return (bool)filter_var($value, \FILTER_VALIDATE_EMAIL); |
|
61 | } |
||
62 | } |
||
63 |