1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Tests\TestEnvironments\Php81\Rule; |
6
|
|
|
|
7
|
|
|
use PHPUnit\Framework\TestCase; |
8
|
|
|
use ReflectionProperty; |
9
|
|
|
use Yiisoft\Validator\Rule\Nested; |
10
|
|
|
use Yiisoft\Validator\Rule\Number; |
11
|
|
|
use Yiisoft\Validator\Tests\Support\Data\NestedClassAttribute; |
12
|
|
|
use Yiisoft\Validator\Tests\Support\Data\ObjectWithDifferentPropertyVisibility; |
13
|
|
|
use Yiisoft\Validator\Validator; |
14
|
|
|
|
15
|
|
|
final class NestedTest extends TestCase |
16
|
|
|
{ |
17
|
|
|
public function dataHandler(): array |
18
|
|
|
{ |
19
|
|
|
return [ |
20
|
|
|
'object' => [ |
21
|
|
|
new class () { |
22
|
|
|
#[Nested(['number' => new Number(max: 7)])] |
23
|
|
|
private ObjectWithDifferentPropertyVisibility $object; |
24
|
|
|
|
25
|
|
|
public function __construct() |
26
|
|
|
{ |
27
|
|
|
$this->object = new ObjectWithDifferentPropertyVisibility(); |
28
|
|
|
} |
29
|
|
|
}, |
30
|
|
|
[ |
31
|
|
|
'object.number' => ['Value must be no greater than 7.'], |
32
|
|
|
], |
33
|
|
|
], |
34
|
|
|
'object-private-only' => [ |
35
|
|
|
new class () { |
36
|
|
|
#[Nested( |
37
|
|
|
['age' => new Number(min: 100, skipOnEmpty: true), 'number' => new Number(max: 7)], |
38
|
|
|
propertyVisibility: ReflectionProperty::IS_PRIVATE |
39
|
|
|
)] |
40
|
|
|
private ObjectWithDifferentPropertyVisibility $object; |
41
|
|
|
|
42
|
|
|
public function __construct() |
43
|
|
|
{ |
44
|
|
|
$this->object = new ObjectWithDifferentPropertyVisibility(); |
45
|
|
|
} |
46
|
|
|
}, |
47
|
|
|
[ |
48
|
|
|
'object.number' => ['Value must be no greater than 7.'], |
49
|
|
|
], |
50
|
|
|
], |
51
|
|
|
]; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @dataProvider dataHandler |
56
|
|
|
*/ |
57
|
|
|
public function testHandler( |
58
|
|
|
object $data, |
59
|
|
|
array $expectedErrorMessagesIndexedByPath, |
60
|
|
|
?bool $expectedIsValid = false |
61
|
|
|
): void { |
62
|
|
|
$result = (new Validator())->validate($data); |
63
|
|
|
|
64
|
|
|
$this->assertSame($expectedIsValid, $result->isValid()); |
65
|
|
|
if (!$expectedIsValid) { |
|
|
|
|
66
|
|
|
$this->assertSame($expectedErrorMessagesIndexedByPath, $result->getErrorMessagesIndexedByPath()); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function testClassAttribute(): void |
71
|
|
|
{ |
72
|
|
|
$result = (new Validator())->validate(new NestedClassAttribute()); |
73
|
|
|
|
74
|
|
|
$this->assertSame( |
75
|
|
|
[ |
76
|
|
|
'a' => ['Value must be no less than 7.'], |
77
|
|
|
'b' => ['Value must be no greater than 1.'], |
78
|
|
|
], |
79
|
|
|
$result->getErrorMessagesIndexedByAttribute() |
80
|
|
|
); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
If an expression can have both
false
, andnull
as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.