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