1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\EmptyCriteria\WhenEmpty; |
8
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
9
|
|
|
use Yiisoft\Validator\Result; |
10
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Validates that the specified value is passed and not empty. |
15
|
|
|
* |
16
|
|
|
* @psalm-import-type EmptyCriteriaType from Required |
17
|
46 |
|
*/ |
18
|
|
|
final class RequiredHandler implements RuleHandlerInterface |
19
|
46 |
|
{ |
20
|
1 |
|
/** |
21
|
|
|
* @var callable |
22
|
|
|
* @psalm-var EmptyCriteriaType |
23
|
45 |
|
*/ |
24
|
45 |
|
private $defaultEmptyCriteria; |
25
|
5 |
|
|
26
|
|
|
/** |
27
|
5 |
|
* @psalm-param EmptyCriteriaType|null $defaultEmptyCriteria |
28
|
|
|
*/ |
29
|
|
|
public function __construct( |
30
|
41 |
|
callable|null $defaultEmptyCriteria = null, |
31
|
26 |
|
) { |
32
|
|
|
$this->defaultEmptyCriteria = $defaultEmptyCriteria ?? new WhenEmpty(trimString: true); |
33
|
|
|
} |
34
|
15 |
|
|
35
|
|
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
36
|
15 |
|
{ |
37
|
|
|
if (!$rule instanceof Required) { |
38
|
|
|
throw new UnexpectedRuleException(Required::class, $rule); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$result = new Result(); |
42
|
|
|
if ($context->isAttributeMissing()) { |
43
|
|
|
$result->addError($rule->getNotPassedMessage(), ['attribute' => $context->getTranslatedAttribute()]); |
44
|
|
|
|
45
|
|
|
return $result; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$emptyCriteria = $rule->getEmptyCriteria() ?? $this->defaultEmptyCriteria; |
49
|
|
|
|
50
|
|
|
if (!$emptyCriteria($value, $context->isAttributeMissing())) { |
51
|
|
|
return $result; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$result->addError($rule->getMessage(), ['attribute' => $context->getTranslatedAttribute()]); |
55
|
|
|
|
56
|
|
|
return $result; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|