Passed
Pull Request — master (#64)
by Alexander
01:27
created

AtLeast::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
c 1
b 0
f 0
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
     * Message to display in case of error.
29
     */
30
    private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.';
31
32
    /**
33
     * @param array $attributes The list of required attributes that will be checked.
34
     */
35 4
    public function __construct(array $attributes)
36
    {
37 4
        $this->attributes = $attributes;
38
    }
39
40 4
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
41
    {
42 4
        $filledCount = 0;
43
44 4
        foreach ($this->attributes as $attribute) {
45 4
            if (!$this->isEmpty($value->{$attribute})) {
46 3
                $filledCount++;
47
            }
48
        }
49
50 4
        $result = new Result();
51
52 4
        if ($filledCount < $this->min) {
53 2
            $result->addError(
54 2
                $this->translateMessage(
55 2
                    $this->message,
56
                    [
57 2
                        'min' => $this->min,
58
                    ]
59
                )
60
            );
61
        }
62
63 4
        return $result;
64
    }
65
66
    public function message(string $message): self
67
    {
68
        $new = clone $this;
69
        $new->message = $message;
70
        return $new;
71
    }
72
73
    /**
74
     * @param int $value The minimum required quantity of filled attributes to pass the validation.
75
     * @return self
76
     */
77 1
    public function min(int $value): self
78
    {
79 1
        $new = clone $this;
80 1
        $new->min = $value;
81 1
        return $new;
82
    }
83
}
84