1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Attribute; |
8
|
|
|
use Closure; |
9
|
|
|
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait; |
10
|
|
|
use Yiisoft\Validator\Rule\Trait\WhenTrait; |
11
|
|
|
use Yiisoft\Validator\SerializableRuleInterface; |
12
|
|
|
use Yiisoft\Validator\EmptyCriteria\WhenEmpty; |
13
|
|
|
use Yiisoft\Validator\SkipOnErrorInterface; |
14
|
|
|
use Yiisoft\Validator\ValidationContext; |
15
|
|
|
use Yiisoft\Validator\WhenInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Validates that the specified value is neither null nor empty. |
19
|
|
|
* |
20
|
|
|
* @psalm-type EmptyCriteriaType = callable(mixed,bool):bool |
21
|
|
|
*/ |
22
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
23
|
|
|
final class Required implements SerializableRuleInterface, SkipOnErrorInterface, WhenInterface |
24
|
|
|
{ |
25
|
|
|
use SkipOnErrorTrait; |
26
|
|
|
use WhenTrait; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var callable |
30
|
|
|
* @psalm-var EmptyCriteriaType |
31
|
|
|
*/ |
32
|
|
|
private $emptyCriteria; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @psalm-param EmptyCriteriaType|null $emptyCriteria |
36
|
|
|
*/ |
37
|
40 |
|
public function __construct( |
38
|
|
|
private string $message = 'Value cannot be blank.', |
39
|
|
|
private string $notPassedMessage = 'Value not passed.', |
40
|
|
|
callable|null $emptyCriteria = null, |
41
|
|
|
private bool $skipOnError = false, |
42
|
|
|
/** |
43
|
|
|
* @var Closure(mixed, ValidationContext):bool|null |
44
|
|
|
*/ |
45
|
|
|
private ?Closure $when = null, |
46
|
|
|
) { |
47
|
40 |
|
$this->emptyCriteria = $emptyCriteria ?? new WhenEmpty(trimString: true); |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
public function getName(): string |
51
|
|
|
{ |
52
|
1 |
|
return 'required'; |
53
|
|
|
} |
54
|
|
|
|
55
|
16 |
|
public function getMessage(): string |
56
|
|
|
{ |
57
|
16 |
|
return $this->message; |
58
|
|
|
} |
59
|
|
|
|
60
|
7 |
|
public function getNotPassedMessage(): string |
61
|
|
|
{ |
62
|
7 |
|
return $this->notPassedMessage; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @psalm-return EmptyCriteriaType |
67
|
|
|
*/ |
68
|
45 |
|
public function getEmptyCriteria(): callable |
69
|
|
|
{ |
70
|
45 |
|
return $this->emptyCriteria; |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
public function getOptions(): array |
74
|
|
|
{ |
75
|
|
|
return [ |
76
|
1 |
|
'message' => $this->message, |
77
|
1 |
|
'notPassedMessage' => $this->notPassedMessage, |
78
|
1 |
|
'skipOnError' => $this->skipOnError, |
79
|
|
|
]; |
80
|
|
|
} |
81
|
|
|
|
82
|
47 |
|
public function getHandlerClassName(): string |
83
|
|
|
{ |
84
|
47 |
|
return RequiredHandler::class; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|