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

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