1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Attribute; |
8
|
|
|
use Closure; |
9
|
|
|
use RuntimeException; |
10
|
|
|
use Yiisoft\Validator\ValidationContext; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Validates if the specified value is equal to another value or attribute. |
14
|
|
|
* |
15
|
|
|
* The value being validated with {@see Equal::$targetValue} or {@see Equal::$targetAttribute}, which |
16
|
|
|
* is set in the constructor. |
17
|
|
|
* |
18
|
|
|
* The default validation function is based on string values, which means the values |
19
|
|
|
* are checked byte by byte. When validating numbers, make sure to change {@see Equal::$type} to |
20
|
|
|
* {@see Equal::TYPE_NUMBER} to enable numeric validation. |
21
|
|
|
*/ |
22
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
23
|
|
|
final class Equal extends Compare |
24
|
|
|
{ |
25
|
3 |
|
public function __construct( |
26
|
|
|
/** |
27
|
|
|
* @var mixed The constant value to be equal to. When both this property |
28
|
|
|
* and {@see $targetAttribute} are set, this property takes precedence. |
29
|
|
|
*/ |
30
|
|
|
private $targetValue = null, |
31
|
|
|
/** |
32
|
|
|
* @var mixed The attribute to be equal to. When both this property |
33
|
|
|
* and {@see $targetValue} are set, the {@see $targetValue} takes precedence. |
34
|
|
|
*/ |
35
|
|
|
private ?string $targetAttribute = null, |
36
|
|
|
/** |
37
|
|
|
* @var string|null User-defined error message. |
38
|
|
|
*/ |
39
|
|
|
private ?string $message = null, |
40
|
|
|
/** |
41
|
|
|
* @var string The type of the values being compared. |
42
|
|
|
*/ |
43
|
|
|
private string $type = self::TYPE_STRING, |
44
|
|
|
/** |
45
|
|
|
* @var bool Whether this validator strictly check. |
46
|
|
|
*/ |
47
|
|
|
private bool $strict = false, |
48
|
|
|
private bool $skipOnEmpty = false, |
49
|
|
|
private bool $skipOnError = false, |
50
|
|
|
/** |
51
|
|
|
* @var Closure(mixed, ValidationContext):bool|null |
52
|
|
|
*/ |
53
|
|
|
private ?Closure $when = null, |
54
|
|
|
) { |
55
|
3 |
|
if ($this->targetValue === null && $this->targetAttribute === null) { |
56
|
1 |
|
throw new RuntimeException('Either "targetValue" or "targetAttribute" must be specified.'); |
57
|
|
|
} |
58
|
2 |
|
parent::__construct( |
59
|
2 |
|
targetValue: $this->targetValue, |
60
|
2 |
|
targetAttribute: $this->targetAttribute, |
61
|
2 |
|
message: $this->message, |
62
|
2 |
|
type: $this->type, |
63
|
2 |
|
operator: $this->strict ? '===' : '==', |
64
|
2 |
|
skipOnEmpty: $this->skipOnEmpty, |
65
|
2 |
|
skipOnError: $this->skipOnError, |
66
|
2 |
|
when: $this->when |
67
|
|
|
); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|