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

CompositeHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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