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

AtLeast::getRawOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
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 7
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\ErrorMessageFormatterInterface;
10
use Yiisoft\Validator\HasValidationErrorMessage;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
14
/**
15
 * AtLeastValidator checks if at least $min of many attributes are filled.
16
 */
17
class AtLeast extends Rule
18
{
19
    use HasValidationErrorMessage;
20
21
    /**
22
     * The minimum required quantity of filled attributes to pass the validation.
23
     * Defaults to 1.
24
     */
25
    private int $min = 1;
26
27
    /**
28
     * The list of required attributes that will be checked.
29
     */
30
    private array $attributes;
31
32
    /**
33
     * Message to display in case of error.
34
     */
35
    private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.';
36
37
    /**
38
     * @param array $attributes The list of required attributes that will be checked.
39
     */
40 5
    public function __construct(array $attributes)
41
    {
42 5
        $this->attributes = $attributes;
43 5
    }
44
45 4
    protected function validateValue($value, DataSetInterface $dataSet = 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
                new ErrorMessage(
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 getRawOptions(): array
84
    {
85 2
        return array_merge(
86 2
            parent::getRawOptions(),
87
            [
88 2
                'min' => $this->min,
89 2
                'message' => new ErrorMessage($this->message, ['min' => $this->min]),
90
            ],
91
        );
92
    }
93
}
94