Passed
Pull Request — master (#222)
by Alexander
04:47 queued 02:23
created

HasLengthValidator::validate()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 5
nop 4
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
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\RuleValidatorInterface;
9
use Yiisoft\Validator\ValidationContext;
10
use Yiisoft\Validator\ValidatorInterface;
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 HasLengthValidator implements RuleValidatorInterface
19
{
20 34
    public function validate($value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
21
    {
22 34
        $result = new Result();
23
24 34
        if (!is_string($value)) {
25 6
            $result->addError($rule->message);
26 6
            return $result;
27
        }
28
29 28
        $length = mb_strlen($value, $rule->encoding);
30
31 28
        if ($rule->min !== null && $length < $rule->min) {
32 5
            $result->addError($rule->tooShortMessage, ['min' => $rule->min]);
33
        }
34 28
        if ($rule->max !== null && $length > $rule->max) {
35 4
            $result->addError($rule->tooLongMessage, ['max' => $rule->max]);
36
        }
37
38 28
        return $result;
39
    }
40
}
41