Passed
Pull Request — master (#293)
by
unknown
16:01 queued 13:39
created

CompositeHandler::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 3
nop 3
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Translator\TranslatorInterface;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\Rule\Trait\PreValidateTrait;
11
use Yiisoft\Validator\RuleHandlerInterface;
12
use Yiisoft\Validator\ValidationContext;
13
14
/**
15
 * Can be used to group rules for validation by `skipOnEmpty`, `skipOnError` or `when`.
16
 *
17
 * For example, we have same when closure:
18
 * ```
19
 * 'name' => [
20
 *     new Required(when: fn() => $this->useName),
21
 *     new HasLength(min: 1, max: 50, skipOnEmpty: true, when: fn() => $this->useName),
22
 * ],
23
 * ```
24
 * So we can configure it like this:
25
 * ```
26
 * 'name' => [
27
 *     new Composite(
28
 *         rules: [
29
 *             new Required(),
30
 *             new HasLength(min: 1, max: 50, skipOnEmpty: true),
31
 *         ],
32
 *         when: fn() => $this->useName,
33
 *     ),
34
 * ],
35
 * ```
36
 */
37
final class CompositeHandler implements RuleHandlerInterface
38
{
39
    use PreValidateTrait;
40
41 7
    public function __construct(private TranslatorInterface $translator)
42
    {
43
    }
44
45 6
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
46
    {
47 6
        if (!$rule instanceof Composite) {
48 1
            throw new UnexpectedRuleException(Composite::class, $rule);
49
        }
50
51 5
        $context->setParameter($this->parameterPreviousRulesErrored, true);
52
53 5
        if ($this->preValidate($value, $context, $rule)) {
54 3
            return new Result();
55
        }
56
57 2
        return $context->getValidator()->validate($value, $rule->getRules());
58
    }
59
}
60