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\SkipOnEmptyCallback\SkipOnEmpty; |
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 EmptyCallback = 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 EmptyCallback |
31
|
|
|
*/ |
32
|
|
|
private $emptyCallback; |
33
|
|
|
|
34
|
37 |
|
public function __construct( |
35
|
|
|
private string $message = 'Value cannot be blank.', |
36
|
|
|
private string $notPassedMessage = 'Value not passed.', |
37
|
|
|
/** |
38
|
|
|
* @var callable |
39
|
|
|
* @psalm-var EmptyCallback |
40
|
|
|
*/ |
41
|
|
|
?callable $emptyCallback = null, |
42
|
|
|
private bool $skipOnError = false, |
43
|
|
|
/** |
44
|
|
|
* @psalm-var Closure(mixed, ValidationContext):bool|null |
45
|
|
|
*/ |
46
|
|
|
private ?Closure $when = null, |
47
|
|
|
) { |
48
|
37 |
|
$this->emptyCallback = $emptyCallback ?? new SkipOnEmpty(); |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
public function getName(): string |
52
|
|
|
{ |
53
|
1 |
|
return 'required'; |
54
|
|
|
} |
55
|
|
|
|
56
|
15 |
|
public function getMessage(): string |
57
|
|
|
{ |
58
|
15 |
|
return $this->message; |
59
|
|
|
} |
60
|
|
|
|
61
|
6 |
|
public function getNotPassedMessage(): string |
62
|
|
|
{ |
63
|
6 |
|
return $this->notPassedMessage; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @psalm-return EmptyCallback |
68
|
|
|
*/ |
69
|
44 |
|
public function getEmptyCallback(): callable |
70
|
|
|
{ |
71
|
44 |
|
return $this->emptyCallback; |
72
|
|
|
} |
73
|
|
|
|
74
|
1 |
|
public function getOptions(): array |
75
|
|
|
{ |
76
|
|
|
return [ |
77
|
1 |
|
'message' => $this->message, |
78
|
1 |
|
'notPassedMessage' => $this->notPassedMessage, |
79
|
1 |
|
'skipOnError' => $this->skipOnError, |
80
|
|
|
]; |
81
|
|
|
} |
82
|
|
|
|
83
|
45 |
|
public function getHandlerClassName(): string |
84
|
|
|
{ |
85
|
45 |
|
return RequiredHandler::class; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|