Passed
Pull Request — master (#222)
by Dmitriy
12:29
created

CountHandler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
wmc 9
eloc 15
dl 0
loc 33
ccs 14
cts 16
cp 0.875
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 31 9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Countable;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use function count;
13
use Yiisoft\Validator\Exception\UnexpectedRuleException;
14
15
/**
16
 * Validates that the value contains certain number of items. Can be applied to arrays or classes implementing
17
 * {@see Countable} interface.
18
 */
19
final class CountHandler implements RuleHandlerInterface
20
{
21 20
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
22
    {
23 20
        if (!$rule instanceof Count) {
24 1
            throw new UnexpectedRuleException(Count::class, $rule);
25
        }
26
27 19
        $result = new Result();
28
29 19
        if (!is_countable($value)) {
30
            $result->addError($rule->message);
31
32
            return $result;
33
        }
34
35 19
        $count = count($value);
36
37 19
        if ($rule->exactly !== null && $count !== $rule->exactly) {
38 1
            $result->addError($rule->notExactlyMessage, ['exactly' => $rule->exactly]);
39
40 1
            return $result;
41
        }
42
43 18
        if ($rule->min !== null && $count < $rule->min) {
44 9
            $result->addError($rule->tooFewItemsMessage, ['min' => $rule->min]);
45
        }
46
47 18
        if ($rule->max !== null && $count > $rule->max) {
48 2
            $result->addError($rule->tooManyItemsMessage, ['max' => $rule->max]);
49
        }
50
51 18
        return $result;
52
    }
53
}
54