Test Failed
Pull Request — master (#364)
by
unknown
03:02
created

StopOnErrorHandler::validate()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0131

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 27
ccs 13
cts 14
cp 0.9286
rs 9.2222
cc 6
nc 10
nop 3
crap 6.0131
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
12
/**
13
 * Can be used for early stopping the validation process of the value when the validation on the stage was failed.
14
 *
15
 * For example, we have several rules, but we want not to process the rest rules when fail was ocurred:
16
 *
17
 * ```php
18
 * $request = [
19
 *     'username' => 'yiisoft',
20
 * ];
21
 * ```
22
 *
23
 * So to make validation we can configure it like this:
24
 *
25
 * ```php
26
 * $rule = new StopOnError([
27
 *      new HasLength(min: 3),
28
 *      // Heavy operation. It would be great not to call it if the previous rule was failed.
29
 *      new ExistsInDatabase(),
30
 * ]);
31
 * ```
32
 */
33
final class StopOnErrorHandler implements RuleHandlerInterface
34
{
35
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
36 5
    {
37
        if (!$rule instanceof StopOnError) {
38 5
            throw new UnexpectedRuleException(StopOnError::class, $rule);
39 1
        }
40
41
        $compoundResult = new Result();
42 4
        $results = [];
43
44
        foreach ($rule->getRules() as $relatedRule) {
45
            $rules = [$relatedRule];
46
47
            $lastResult = $context->getValidator()->validate($value, $rules);
48 4
            $results[] = $lastResult;
49 4
50
            if (!$lastResult->isValid()) {
51 4
                break;
52 4
            }
53
        }
54 4
55 1
        foreach ($results as $result) {
56
            foreach ($result->getErrors() as $error) {
57
                $compoundResult->addError($error->getMessage(), $error->getParameters(), $error->getValuePath());
58 4
            }
59 4
        }
60
61 4
        return $compoundResult;
62 3
    }
63
}
64