Passed
Push — master ( 99ab46...a20a6f )
by Alexander
02:59
created

AtLeast::rule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\HasValidationErrorMessage;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\ValidationContext;
11
12
/**
13
 * AtLeastValidator checks if at least $min of many attributes are filled.
14
 */
15
class AtLeast extends Rule
16
{
17
    use HasValidationErrorMessage;
18
19
    /**
20
     * The minimum required quantity of filled attributes to pass the validation.
21
     * Defaults to 1.
22
     */
23
    private int $min = 1;
24
25
    /**
26
     * The list of required attributes that will be checked.
27
     */
28
    private array $attributes;
29
30
    /**
31
     * Message to display in case of error.
32
     */
33
    private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.';
34
35
    /**
36
     * @param array $attributes The list of required attributes that will be checked.
37
     */
38 5
    public static function rule(array $attributes): self
39
    {
40 5
        $rule = new self();
41 5
        $rule->attributes = $attributes;
42 5
        return $rule;
43
    }
44
45 4
    protected function validateValue($value, ValidationContext $context = null): Result
46
    {
47 4
        $filledCount = 0;
48
49 4
        foreach ($this->attributes as $attribute) {
50 4
            if (!$this->isEmpty($value->{$attribute})) {
51 3
                $filledCount++;
52
            }
53
        }
54
55 4
        $result = new Result();
56
57 4
        if ($filledCount < $this->min) {
58 2
            $result->addError(
59 2
                $this->formatMessage(
60 2
                    $this->message,
61
                    [
62 2
                        'min' => $this->min,
63
                    ]
64
                )
65
            );
66
        }
67
68 4
        return $result;
69
    }
70
71
    /**
72
     * @param int $value The minimum required quantity of filled attributes to pass the validation.
73
     *
74
     * @return self
75
     */
76 1
    public function min(int $value): self
77
    {
78 1
        $new = clone $this;
79 1
        $new->min = $value;
80 1
        return $new;
81
    }
82
83 2
    public function getOptions(): array
84
    {
85 2
        return array_merge(
86 2
            parent::getOptions(),
87 2
            ['min' => $this->min],
88 2
            ['message' => $this->formatMessage($this->message, ['min' => $this->min])],
89
        );
90
    }
91
}
92