Passed
Pull Request — master (#175)
by
unknown
02:24
created

AtLeast   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 50
ccs 16
cts 16
cp 1
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validateValue() 0 18 4
A getOptions() 0 5 1
A __construct() 0 20 1
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 5
    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
41 4
    protected function validateValue($value, ?ValidationContext $context = null): Result
42
    {
43 4
        $filledCount = 0;
44
45 4
        foreach ($this->attributes as $attribute) {
46 4
            if (!$this->isEmpty($value->{$attribute})) {
47 3
                $filledCount++;
48
            }
49
        }
50
51 4
        $result = new Result();
52
53 4
        if ($filledCount < $this->min) {
54 2
            $message = $this->formatMessage($this->message, ['min' => $this->min]);
55 2
            $result->addError($message);
56
        }
57
58 4
        return $result;
59
    }
60
61 2
    public function getOptions(): array
62
    {
63 2
        return array_merge(parent::getOptions(), [
64 2
            'min' => $this->min,
65 2
            'message' => $this->formatMessage($this->message, ['min' => $this->min]),
66
        ]);
67
    }
68
}
69