Passed
Pull Request — master (#222)
by Rustam
02:34
created

HasLengthHandler::validate()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 35
ccs 22
cts 22
cp 1
rs 8.6506
c 0
b 0
f 0
cc 7
nc 6
nop 3
crap 7
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\Formatter;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
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
    private FormatterInterface $formatter;
23
24 35
    public function __construct(?FormatterInterface $formatter = null)
25
    {
26 35
        $this->formatter = $formatter ?? new Formatter();
27
    }
28
29 35
    public function validate($value, object $rule, ?ValidationContext $context = null): Result
30
    {
31 35
        if (!$rule instanceof HasLength) {
32 1
            throw new UnexpectedRuleException(HasLength::class, $rule);
33
        }
34
35 34
        $result = new Result();
36
37 34
        if (!is_string($value)) {
38 6
            $formattedMessage = $this->formatter->format(
39 6
                $rule->getMessage(),
40 6
                ['attribute' => $context?->getAttribute(), 'value' => $value]
41
            );
42 6
            $result->addError($formattedMessage);
43 6
            return $result;
44
        }
45
46 28
        $length = mb_strlen($value, $rule->getEncoding());
47
48 28
        if ($rule->getMin() !== null && $length < $rule->getMin()) {
49 5
            $formattedMessage = $this->formatter->format(
50 5
                $rule->getTooShortMessage(),
51 5
                ['min' => $rule->getMin(), 'attribute' => $context?->getAttribute(), 'value' => $value]
52
            );
53 5
            $result->addError($formattedMessage);
54
        }
55 28
        if ($rule->getMax() !== null && $length > $rule->getMax()) {
56 4
            $formattedMessage = $this->formatter->format(
57 4
                $rule->getTooLongMessage(),
58 4
                ['max' => $rule->getMax(), 'attribute' => $context?->getAttribute(), 'value' => $value]
59
            );
60 4
            $result->addError($formattedMessage);
61
        }
62
63 28
        return $result;
64
    }
65
}
66