Passed
Pull Request — master (#64)
by
unknown
07:43
created

AtLeast   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 63
rs 10
ccs 20
cts 20
cp 1
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A validateValue() 0 27 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Rule;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\DataSetInterface;
10
11
/**
12
 * AtLeastValidator checks if at least $min of many attributes are filled.
13
 */
14
class AtLeast extends Rule
15
{
16
    /**
17
     * The minimum required quantity of filled attributes to pass the validation.
18
     * Defaults to 1.
19
     */
20
    private int $min = 1;
21
22
    /**
23
     * The list of required attributes that will be checked.
24
     */
25
    private array $attributes = [];
26
27
    /**
28
     * The list of alternative required attributes that will be checked.
29
     */
30
    private array $alternativeAttributes = [];
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 6
    public function __construct(array $data)
38
    {
39 6
        foreach ($data as $name => $value) {
40 6
            $this->{$name} = $value;
41
        }
42
43 6
        if (empty($this->alternativeAttributes)) {
44 2
            $this->alternativeAttributes = $this->attributes;
45
        } else {
46 4
            $this->alternativeAttributes = array_merge($this->attributes, $this->alternativeAttributes);
47
        }
48
    }
49
50 6
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
51
    {
52 6
        $valid = false;
53 6
        $filledCount = 0;
54
55 6
        foreach ($this->alternativeAttributes as $attribute) {
56 5
            $filledCount += $this->isEmpty($value->{$attribute}) ? 0 : 1;
57
        }
58
59 6
        if ($filledCount >= $this->min) {
60 3
            $valid = true;
61
        }
62
63 6
        $result = new Result();
64
65 6
        if (!$valid) {
66 3
            $result->addError(
67 3
                $this->translateMessage(
68 3
                    $this->message,
69
                    [
70 3
                        'min' => $this->min,
71
                    ]
72
                )
73
            );
74
        }
75
76 6
        return $result;
77
    }
78
}
79