Passed
Push — master ( c644e1...919d8c )
by Alexander
04:16 queued 01:42
created

LimitHandlerTrait::validateLimits()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 31
ccs 17
cts 17
cp 1
rs 8.8333
cc 7
nc 5
nop 5
crap 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Trait;
6
7
use Yiisoft\Validator\Result;
8
use Yiisoft\Validator\ValidationContext;
9
10
/**
11
 * A trait attachable to a handler of rule with limits.
12
 */
13
trait LimitHandlerTrait
14
{
15
    /**
16
     * Runs limits specific validation.
17
     *
18
     * @param mixed $value A validated value in its raw form.
19
     * @param object $rule A rule matching to this handler.
20
     * @param ValidationContext $context Validation context.
21
     * @param int $number A validated number to compare with set limits.
22
     * @param Result $result Result for adding errors.
23
     *
24
     * @see LimitTrait for information about limits and messages.
25
     */
26 43
    private function validateLimits(
27
        mixed $value,
28
        object $rule,
29
        ValidationContext $context,
30
        int $number,
31
        Result $result
32
    ): void {
33 43
        if ($rule->getExactly() !== null && $number !== $rule->getExactly()) {
34 3
            $formattedMessage = $this->formatter->format(
35 3
                $rule->getNotExactlyMessage(),
36 3
                ['exactly' => $rule->getExactly(), 'attribute' => $context->getAttribute(), 'value' => $value]
37
            );
38 3
            $result->addError($formattedMessage);
39
40 3
            return;
41
        }
42
43 40
        if ($rule->getMin() !== null && $number < $rule->getMin()) {
44 13
            $formattedMessage = $this->formatter->format(
45 13
                $rule->getLessThanMinMessage(),
46 13
                ['min' => $rule->getMin(), 'attribute' => $context->getAttribute(), 'value' => $value]
47
            );
48 13
            $result->addError($formattedMessage);
49
        }
50
51 40
        if ($rule->getMax() !== null && $number > $rule->getMax()) {
52 4
            $formattedMessage = $this->formatter->format(
53 4
                $rule->getGreaterThanMaxMessage(),
54 4
                ['max' => $rule->getMax(), 'attribute' => $context->getAttribute(), 'value' => $value]
55
            );
56 4
            $result->addError($formattedMessage);
57
        }
58
    }
59
}
60