Completed
Push — master ( 7d90f1...0c951c )
by John
03:40
created

SchemaValidatorAdapter::validate()   D

Complexity

Conditions 9
Paths 2

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 4.909
c 0
b 0
f 0
cc 9
eloc 22
nc 2
nop 4
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of the KleijnWeb\PhpApi\Descriptions package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\PhpApi\Descriptions\Description\Schema\Validator;
10
11
use KleijnWeb\PhpApi\Descriptions\Description\Schema\Schema;
12
13
/**
14
 * @author John Kleijn <[email protected]>
15
 */
16
abstract class SchemaValidatorAdapter implements SchemaValidator
17
{
18
    /**
19
     * @param Schema $schema
20
     * @param mixed  $value
21
     * @param bool   $forceNoAdditionalProperties
22
     * @param bool   $requireAllWhenNotSpecified
23
     *
24
     * @return ValidationResult
25
     */
26
    public function validate(
27
        Schema $schema,
28
        $value,
29
        $forceNoAdditionalProperties = false,
30
        $requireAllWhenNotSpecified = false
31
    ): ValidationResult {
32
33
        $definition = $schema->getDefinition();
34
35
        if ($requireAllWhenNotSpecified || $forceNoAdditionalProperties) {
36
            $hackDefinition = function (\stdClass $definition) use (
37
                $forceNoAdditionalProperties,
38
                $requireAllWhenNotSpecified,
39
                &$hackDefinition
40
            ) {
41
                if (isset($definition->properties)) {
42
                    if ($forceNoAdditionalProperties) {
43
                        $definition->additionalProperties = false;
44
                    }
45
                    if ($requireAllWhenNotSpecified && !isset($definition->required)) {
46
                        $definition->required = array_keys((array)$definition->properties);
47
                    }
48
                }
49
50
                foreach ($definition as $item) {
0 ignored issues
show
Bug introduced by
The expression $definition of type object<stdClass> is not traversable.
Loading history...
51
                    if ($item instanceof \stdClass) {
52
                        $hackDefinition($item);
53
                    }
54
                }
55
            };
56
            $hackDefinition($definition = clone $definition);
57
        }
58
59
        return $this->getResult($definition, $value);
60
    }
61
62
    abstract protected function getResult(\stdClass $definition, $value): ValidationResult;
63
}
64