Passed
Pull Request — master (#300)
by Alexander
06:13 queued 03:06
created

Composite   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 21
c 1
b 0
f 0
dl 0
loc 59
ccs 12
cts 13
cp 0.9231
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
A getOptions() 0 20 3
A getRules() 0 3 1
A getHandlerClassName() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Closure;
9
use JetBrains\PhpStorm\ArrayShape;
10
use Yiisoft\Validator\BeforeValidationInterface;
11
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait;
12
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
13
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
14
use Yiisoft\Validator\RuleInterface;
15
use Yiisoft\Validator\SerializableRuleInterface;
16
use Yiisoft\Validator\SkipOnEmptyInterface;
17
use Yiisoft\Validator\ValidationContext;
18
19
/**
20
 * Allows to combine and validate multiple rules.
21
 */
22
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
23
class Composite implements SerializableRuleInterface, BeforeValidationInterface, SkipOnEmptyInterface
24
{
25
    use BeforeValidationTrait;
26
    use RuleNameTrait;
27
    use SkipOnEmptyTrait;
28
29 2
    public function __construct(
30
        /**
31
         * @var iterable<RuleInterface>
32
         */
33
        private iterable $rules = [],
34
35
        /**
36
         * @var bool|callable|null
37
         */
38
        private $skipOnEmpty = null,
39
        private bool $skipOnError = false,
40
        /**
41
         * @var Closure(mixed, ValidationContext):bool|null
42
         */
43
        private ?Closure $when = null,
44
    ) {
45
    }
46
47 1
    #[ArrayShape([
48
        'skipOnEmpty' => 'bool',
49
        'skipOnError' => 'bool',
50
        'rules' => 'array',
51
    ])]
52
    public function getOptions(): array
53
    {
54 1
        $arrayOfRules = [];
55 1
        foreach ($this->getRules() as $rule) {
56 1
            if ($rule instanceof SerializableRuleInterface) {
57 1
                $arrayOfRules[] = array_merge([$rule->getName()], $rule->getOptions());
58
            } else {
59
                $arrayOfRules[] = [$rule->getName()];
60
            }
61
        }
62
63
        return [
64 1
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
65 1
            'skipOnError' => $this->skipOnError,
66
            'rules' => $arrayOfRules,
67
        ];
68
    }
69
70
    /**
71
     * @return iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
72
     */
73 3
    public function getRules(): iterable
74
    {
75 3
        return $this->rules;
76
    }
77
78 1
    public function getHandlerClassName(): string
79
    {
80 1
        return CompositeHandler::class;
81
    }
82
}
83