Passed
Pull Request — master (#99)
by Def
02:19
created

AtLeast::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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