Skip to content

Commit 62cd3fa

Browse files
authored
Add WhenMissing empty criteria (#500)
1 parent e250324 commit 62cd3fa

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

src/EmptyCriteria/WhenMissing.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yiisoft\Validator\EmptyCriteria;
6+
7+
/**
8+
* Empty criteria is a callable returning `true` if a value must be considered empty.
9+
*
10+
* With `WhenMissing` a rule is considered empty only when the value is missing. With regard to validation process, a
11+
* corresponding rule is skipped only if this condition is met and `WhenMissing` is set:
12+
*
13+
* - At a rule level via `$skipOnEmpty` property, but only for rules implementing {@see SkipOnEmptyTrait} / including
14+
* {@see SkipOnEmptyTrait}.
15+
* - At validator level ({@see Validator::$defaultSkipOnEmptyCriteria}).
16+
*
17+
* There is no shortcut for this criteria, because it's considered less used. Use new instance directly:
18+
* `new WhenMissing()`.
19+
*/
20+
final class WhenMissing
21+
{
22+
/**
23+
* @param mixed $value The validated value.
24+
* @param bool $isAttributeMissing A flag defining whether the attribute is missing (not used / not passed at all).
25+
*
26+
* @return bool Whether the validated value is considered empty.
27+
*/
28+
public function __invoke(mixed $value, bool $isAttributeMissing): bool
29+
{
30+
return $isAttributeMissing;
31+
}
32+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Yiisoft\Validator\Tests\EmptyCriteria;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Yiisoft\Validator\EmptyCriteria\WhenMissing;
9+
use Yiisoft\Validator\Rule\Number;
10+
use Yiisoft\Validator\RuleInterface;
11+
use Yiisoft\Validator\Validator;
12+
13+
final class WhenMissingTest extends TestCase
14+
{
15+
public function dataBase(): array
16+
{
17+
return [
18+
[
19+
['The allowed types are integer, float and string.'],
20+
null,
21+
new Number(skipOnEmpty: new WhenMissing()),
22+
],
23+
[
24+
[],
25+
[],
26+
['property' => new Number(skipOnEmpty: new WhenMissing())],
27+
],
28+
[
29+
['Value must be a number.'],
30+
'',
31+
new Number(skipOnEmpty: new WhenMissing()),
32+
],
33+
];
34+
}
35+
36+
/**
37+
* @dataProvider dataBase
38+
*/
39+
public function testBase(array $expectedMessages, mixed $data, array|RuleInterface|null $rules = null): void
40+
{
41+
$result = (new Validator())->validate($data, $rules);
42+
43+
$this->assertSame($expectedMessages, $result->getErrorMessages());
44+
}
45+
}

0 commit comments

Comments
 (0)