Test Setup Failed
Push — master ( e94fe5...b7ec94 )
by
unknown
02:01
created

AtLeast::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 7
dl 0
loc 20
ccs 1
cts 1
cp 1
crap 1
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 Attribute;
8
use Yiisoft\Validator\FormatterInterface;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\Rule;
11
use Yiisoft\Validator\ValidationContext;
12
13
/**
14
 * Checks if at least {@see AtLeast::$min} of many attributes are filled.
15
 */
16
#[Attribute(Attribute::TARGET_PROPERTY)]
17
final class AtLeast extends Rule
18
{
19
    public function __construct(
20
        /**
21
         * The list of required attributes that will be checked.
22
         */
23
        private array $attributes,
24
        /**
25
         * The minimum required quantity of filled attributes to pass the validation.
26
         * Defaults to 1.
27
         */
28
        private int $min = 1,
29
        /**
30
         * Message to display in case of error.
31
         */
32
        private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.',
33
        ?FormatterInterface $formatter = null,
34
        bool $skipOnEmpty = false,
35
        bool $skipOnError = false,
36
        $when = null
37
    ) {
38 5
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
39
    }
40 5
41 5
    protected function validateValue($value, ?ValidationContext $context = null): Result
42 5
    {
43
        $filledCount = 0;
44
45 4
        foreach ($this->attributes as $attribute) {
46
            if (!$this->isEmpty($value->{$attribute})) {
47 4
                $filledCount++;
48
            }
49 4
        }
50 4
51 3
        $result = new Result();
52
53
        if ($filledCount < $this->min) {
54
            $message = $this->formatMessage($this->message, ['min' => $this->min]);
55 4
            $result->addError($message);
56
        }
57 4
58 2
        return $result;
59 2
    }
60 2
61
    public function getOptions(): array
62 2
    {
63
        return array_merge(parent::getOptions(), [
64
            'min' => $this->min,
65
            'message' => $this->formatMessage($this->message, ['min' => $this->min]),
66
        ]);
67
    }
68
}
69