Passed
Pull Request — master (#333)
by Sergei
02:38
created

Composite::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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