Passed
Push — master ( 5c2907...37dc07 )
by Sergei
24:35 queued 21:56
created

HasLengthHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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 of certain length.
17
 *
18
 * Note, this rule should only be used with strings.
19
 */
20
final class HasLengthHandler implements RuleHandlerInterface
21
{
22
    use LimitHandlerTrait;
23
24 64
    public function validate($value, object $rule, ValidationContext $context): Result
25
    {
26 64
        if (!$rule instanceof HasLength) {
27 1
            throw new UnexpectedRuleException(HasLength::class, $rule);
28
        }
29
30 63
        $result = new Result();
31
32 63
        if (!is_string($value)) {
33 5
            $result->addError(
34 5
                $rule->getMessage(),
35
                [
36 5
                    'attribute' => $context->getAttribute(),
37
                    'value' => $value,
38
                ],
39
            );
40 5
            return $result;
41
        }
42
43 58
        $length = mb_strlen($value, $rule->getEncoding());
44 58
        $this->validateLimits($value, $rule, $context, $length, $result);
45
46 58
        return $result;
47
    }
48
}
49