Passed
Pull Request — master (#519)
by
unknown
03:06
created

LengthHandler::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 20
cc 3
rs 9.9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\Trait\LimitHandlerTrait;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
13
use function is_string;
14
15
/**
16
 * Validates that the value is a string of a certain length.
17
 *
18
 * @see Length
19
 */
20
final class LengthHandler implements RuleHandlerInterface
21
{
22
    use LimitHandlerTrait;
23
24
    public function validate($value, object $rule, ValidationContext $context): Result
25
    {
26
        if (!$rule instanceof Length) {
27
            throw new UnexpectedRuleException(Length::class, $rule);
28
        }
29
30
        $result = new Result();
31
        if (!is_string($value)) {
32
            $result->addError($rule->getIncorrectInputMessage(), [
33
                'attribute' => $context->getTranslatedAttribute(),
34
                'type' => get_debug_type($value),
35
            ]);
36
37
            return $result;
38
        }
39
40
        $length = mb_strlen($value, $rule->getEncoding());
41
        $this->validateLimits($rule, $context, $length, $result);
42
43
        return $result;
44
    }
45
}
46