OneOfConstraint::apply()   C
last analyzed

Complexity

Conditions 7
Paths 16

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 30
c 0
b 0
f 0
ccs 23
cts 23
cp 1
rs 6.7272
cc 7
eloc 19
nc 16
nop 4
crap 7
1
<?php
2
3
/*
4
 * This file is part of the JVal package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace JVal\Constraint;
11
12
use JVal\Context;
13
use JVal\Walker;
14
use stdClass;
15
16
/**
17
 * Constraint for the "oneOf" keyword.
18
 */
19
class OneOfConstraint extends AbstractOfConstraint
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24 377
    public function keywords()
25
    {
26 377
        return ['oneOf'];
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 21
    public function apply($instance, stdClass $schema, Context $context, Walker $walker)
33
    {
34 21
        $accumulatingContext = $context->duplicate(false);
35 21
        $hasMatch = false;
36 21
        $hasDoubleMatch = false;
37
38 21
        foreach ($schema->oneOf as $subSchema) {
39 21
            $subContext = $context->duplicate(false);
40 21
            $walker->applyConstraints($instance, $subSchema, $subContext);
41
42 21
            if ($subContext->countViolations() === 0) {
43 16
                if (!$hasMatch) {
44 16
                    $hasMatch = true;
45 16
                } else {
46 4
                    $hasDoubleMatch = true;
47 4
                    break;
48
                }
49 16
            } else {
50 14
                $accumulatingContext->mergeViolations($subContext);
51
            }
52 21
        }
53
54 21
        if (!$hasMatch) {
55 6
            $context->mergeViolations($accumulatingContext);
56 6
        }
57
58 21
        if (!$hasMatch || $hasDoubleMatch) {
59 10
            $context->addViolation('instance must match exactly one of the schemas listed in oneOf');
60 10
        }
61 21
    }
62
}
63