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

HasLengthHandler::validate()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 8.8333
cc 7
nc 6
nop 3
crap 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\ValidatorInterface;
10
use Yiisoft\Validator\Exception\UnexpectedRuleException;
11
use function is_string;
12
13
/**
14
 * Validates that the value is of certain length.
15
 *
16
 * Note, this rule should only be used with strings.
17
 */
18
final class HasLengthHandler implements RuleHandlerInterface
19
{
20 35
    public function validate($value, object $rule, ?ValidationContext $context = null): Result
21
    {
22 35
        if (!$rule instanceof HasLength) {
23 1
            throw new UnexpectedRuleException(HasLength::class, $rule);
24
        }
25
26 34
        $result = new Result();
27
28 34
        if (!is_string($value)) {
29 6
            $result->addError($rule->message);
30 6
            return $result;
31
        }
32
33 28
        $length = mb_strlen($value, $rule->encoding);
34
35 28
        if ($rule->min !== null && $length < $rule->min) {
36 5
            $result->addError($rule->tooShortMessage, ['min' => $rule->min]);
37
        }
38 28
        if ($rule->max !== null && $length > $rule->max) {
39 4
            $result->addError($rule->tooLongMessage, ['max' => $rule->max]);
40
        }
41
42 28
        return $result;
43
    }
44
}
45