Passed
Pull Request — master (#462)
by Sergei
02:28
created

RequiredHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\EmptyCriteria\WhenEmpty;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
13
/**
14
 * Validates that the specified value is passed and not empty.
15
 *
16
 * @psalm-import-type EmptyCriteriaType from Required
17 46
 */
18
final class RequiredHandler implements RuleHandlerInterface
19 46
{
20 1
    /**
21
     * @var callable
22
     * @psalm-var EmptyCriteriaType
23 45
     */
24 45
    private $defaultEmptyCriteria;
25 5
26
    /**
27 5
     * @psalm-param EmptyCriteriaType|null $defaultEmptyCriteria
28
     */
29
    public function __construct(
30 41
        callable|null $defaultEmptyCriteria = null,
31 26
    ) {
32
        $this->defaultEmptyCriteria = $defaultEmptyCriteria ?? new WhenEmpty(trimString: true);
33
    }
34 15
35
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
36 15
    {
37
        if (!$rule instanceof Required) {
38
            throw new UnexpectedRuleException(Required::class, $rule);
39
        }
40
41
        $result = new Result();
42
        if ($context->isAttributeMissing()) {
43
            $result->addError($rule->getNotPassedMessage(), ['attribute' => $context->getTranslatedAttribute()]);
44
45
            return $result;
46
        }
47
48
        $emptyCriteria = $rule->getEmptyCriteria() ?? $this->defaultEmptyCriteria;
49
50
        if (!$emptyCriteria($value, $context->isAttributeMissing())) {
51
            return $result;
52
        }
53
54
        $result->addError($rule->getMessage(), ['attribute' => $context->getTranslatedAttribute()]);
55
56
        return $result;
57
    }
58
}
59