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

RequiredHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 12
c 1
b 0
f 0
dl 0
loc 26
ccs 13
cts 13
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 24 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