Passed
Pull Request — master (#288)
by Alexander
10:50 queued 07:32
created

Composite::getOptions()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 20
ccs 7
cts 8
cp 0.875
rs 9.7998
cc 3
nc 3
nop 0
crap 3.0175
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\RuleInterface;
14
use Yiisoft\Validator\SerializableRuleInterface;
15
use Yiisoft\Validator\ValidationContext;
16
17
/**
18
 * Allows to combine and validate multiple rules.
19
 */
20
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
21
class Composite implements SerializableRuleInterface, BeforeValidationInterface
22
{
23
    use BeforeValidationTrait;
24
    use RuleNameTrait;
25
26 2
    public function __construct(
27
        /**
28
         * @var iterable<RuleInterface>
29
         */
30
        private iterable $rules = [],
31
        private bool $skipOnEmpty = false,
32
        private $skipOnEmptyCallback = null,
33
        private bool $skipOnError = false,
34
        /**
35
         * @var Closure(mixed, ValidationContext):bool|null
36
         */
37
        private ?Closure $when = null,
38
    ) {
39 2
        $this->initSkipOnEmptyProperties($skipOnEmpty, $skipOnEmptyCallback);
40
    }
41
42 1
    #[ArrayShape([
43
        'skipOnEmpty' => 'bool',
44
        'skipOnError' => 'bool',
45
        'rules' => 'array',
46
    ])]
47
    public function getOptions(): array
48
    {
49 1
        $arrayOfRules = [];
50 1
        foreach ($this->getRules() as $rule) {
51 1
            if ($rule instanceof SerializableRuleInterface) {
52 1
                $arrayOfRules[] = array_merge([$rule->getName()], $rule->getOptions());
53
            } else {
54
                $arrayOfRules[] = [$rule->getName()];
55
            }
56
        }
57
58
        return [
59 1
            'skipOnEmpty' => $this->skipOnEmpty,
60 1
            'skipOnError' => $this->skipOnError,
61
            'rules' => $arrayOfRules,
62
        ];
63
    }
64
65
    /**
66
     * @return iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
67
     */
68 3
    public function getRules(): iterable
69
    {
70 3
        return $this->rules;
71
    }
72
73 1
    public function getHandlerClassName(): string
74
    {
75 1
        return CompositeHandler::class;
76
    }
77
}
78