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

RequiredHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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