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

AtLeast   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 24
c 2
b 1
f 0
dl 0
loc 73
ccs 24
cts 24
cp 1
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A min() 0 5 1
A __construct() 0 3 1
A validateValue() 0 24 4
A getRawOptions() 0 7 1
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