1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Tests; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\Rules; |
8
|
|
|
use PHPUnit\Framework\TestCase; |
9
|
|
|
use Yiisoft\Validator\Result; |
10
|
|
|
use Yiisoft\Validator\Rule\Number; |
11
|
|
|
use Yiisoft\Validator\Rule\Required; |
12
|
|
|
|
13
|
|
|
class RulesTest extends TestCase |
14
|
|
|
{ |
15
|
|
|
public function testMethodSyntax(): void |
16
|
|
|
{ |
17
|
|
|
$rules = new Rules(); |
18
|
|
|
$rules->add(new Required()); |
19
|
|
|
$rules->add((new Number())->max(10)); |
20
|
|
|
|
21
|
|
|
$result = $rules->validate(42); |
22
|
|
|
$this->assertFalse($result->isValid()); |
23
|
|
|
$this->assertCount(1, $result->getErrors()); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function testArraySyntax(): void |
27
|
|
|
{ |
28
|
|
|
$rules = new Rules( |
29
|
|
|
[ |
30
|
|
|
new Required(), |
31
|
|
|
(new Number())->max(10) |
32
|
|
|
] |
33
|
|
|
); |
34
|
|
|
|
35
|
|
|
$result = $rules->validate(42); |
36
|
|
|
$this->assertFalse($result->isValid()); |
37
|
|
|
$this->assertCount(1, $result->getErrors()); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function testCallback(): void |
41
|
|
|
{ |
42
|
|
|
$rules = new Rules( |
43
|
|
|
[ |
44
|
|
|
static function ($value): Result { |
45
|
|
|
$result = new Result(); |
46
|
|
|
if ($value !== 42) { |
47
|
|
|
$result->addError('Value should be 42!'); |
48
|
|
|
} |
49
|
|
|
return $result; |
50
|
|
|
} |
51
|
|
|
] |
52
|
|
|
); |
53
|
|
|
|
54
|
|
|
$result = $rules->validate(41); |
55
|
|
|
$this->assertFalse($result->isValid()); |
56
|
|
|
$this->assertCount(1, $result->getErrors()); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function testWhenValidate() |
60
|
|
|
{ |
61
|
|
|
$rules = new Rules( |
62
|
|
|
[ |
63
|
|
|
(new Number())->min(10), |
64
|
|
|
(new Number())->min(10)->when(fn () => false)->skipOnError(false), |
65
|
|
|
(new Number())->min(10)->skipOnError(false) |
66
|
|
|
] |
67
|
|
|
); |
68
|
|
|
|
69
|
|
|
$result = $rules->validate(1); |
70
|
|
|
|
71
|
|
|
$this->assertFalse($result->isValid()); |
72
|
|
|
$this->assertCount(2, $result->getErrors()); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function testSkipOnError() |
76
|
|
|
{ |
77
|
|
|
$rules = new Rules( |
78
|
|
|
[ |
79
|
|
|
(new Number())->min(10), |
80
|
|
|
(new Number())->min(10)->skipOnError(false), |
81
|
|
|
(new Number())->min(10) |
82
|
|
|
] |
83
|
|
|
); |
84
|
|
|
|
85
|
|
|
$result = $rules->validate(1); |
86
|
|
|
|
87
|
|
|
$this->assertFalse($result->isValid()); |
88
|
|
|
$this->assertCount(2, $result->getErrors()); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|