Test Setup Failed
Pull Request — master (#216)
by Dmitriy
03:06
created

HasLengthValidator::validate()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 19
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 function is_string;
11
12
/**
13
 * Validates that the value is of certain length.
14
 *
15
 * Note, this rule should only be used with strings.
16
 */
17
final class HasLengthValidator implements RuleValidatorInterface
18
{
19
    public function __construct(
20
    ) {
21
    }
22
23
    /**
24
     * @param $value
25
     * @param HasLength $config
26
     * @param ValidationContext|null $context
27
     *
28
     * @return Result
29
     */
30
    public function validate($value, object $config, ?ValidationContext $context = null): Result
31
    {
32
        $result = new Result();
33
34
        if (!is_string($value)) {
35
            $result->addError($config->message);
36
            return $result;
37
        }
38
39
        $length = mb_strlen($value, $config->encoding);
40
41
        if ($config->min !== null && $length < $config->min) {
42
            $result->addError($config->tooShortMessage, ['min' => $config->min]);
43
        }
44
        if ($config->max !== null && $length > $config->max) {
45
            $result->addError($config->tooLongMessage, ['max' => $config->max]);
46
        }
47
48
        return $result;
49
    }
50
}
51