Passed
Push — master ( 5c2907...37dc07 )
by Sergei
24:35 queued 21:56
created

RequiredHandler::validate()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 24
ccs 13
cts 13
cp 1
rs 9.5555
cc 5
nc 6
nop 3
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\SkipOnEmptyCallback\SkipOnEmpty;
11
use Yiisoft\Validator\ValidationContext;
12
13
use function is_string;
14
15
/**
16
 * Validates that the specified value is passed and not empty.
17
 */
18
final class RequiredHandler implements RuleHandlerInterface
19
{
20 45
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
21
    {
22 45
        if (!$rule instanceof Required) {
23 1
            throw new UnexpectedRuleException(Required::class, $rule);
24
        }
25
26 44
        $result = new Result();
27 44
        if ($context->isAttributeMissing()) {
28 5
            $result->addError($rule->getNotPassedMessage());
29
30 5
            return $result;
31
        }
32
33 40
        if (is_string($value)) {
34 19
            $value = trim($value);
35
        }
36
37 40
        if (!(new SkipOnEmpty())($value, $context->isAttributeMissing())) {
38 25
            return $result;
39
        }
40
41 15
        $result->addError($rule->getMessage());
42
43 15
        return $result;
44
    }
45
}
46