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

HasLengthValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 21
ccs 11
cts 11
cp 1
rs 10
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 19 6
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