Passed
Pull Request — master (#222)
by Dmitriy
02:35
created

HasLengthHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 12
dl 0
loc 25
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 23 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Result;
8
use Yiisoft\Validator\ValidationContext;
9
use Yiisoft\Validator\Exception\UnexpectedRuleException;
10
use function is_string;
11
12
/**
13
 * Validates that the value is of certain length.
14
 *
15
 * Note, this rule should only be used with strings.
16
 */
17
final class HasLengthHandler implements RuleHandlerInterface
18
{
19 35
    public function validate($value, object $rule, ?ValidationContext $context = null): Result
20
    {
21 35
        if (!$rule instanceof HasLength) {
22 1
            throw new UnexpectedRuleException(HasLength::class, $rule);
23
        }
24
25 34
        $result = new Result();
26
27 34
        if (!is_string($value)) {
28 6
            $result->addError($rule->message);
29 6
            return $result;
30
        }
31
32 28
        $length = mb_strlen($value, $rule->encoding);
33
34 28
        if ($rule->min !== null && $length < $rule->min) {
35 5
            $result->addError($rule->tooShortMessage, ['min' => $rule->min]);
36
        }
37 28
        if ($rule->max !== null && $length > $rule->max) {
38 4
            $result->addError($rule->tooLongMessage, ['max' => $rule->max]);
39
        }
40
41 28
        return $result;
42
    }
43
}
44