DocumentValidator::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 3
eloc 6
c 2
b 0
f 1
nc 3
nop 1
dl 0
loc 11
rs 10
ccs 6
cts 6
cp 1
crap 3
1
<?php
2
3
namespace erasys\OpenApi\Validator;
4
5
use erasys\OpenApi\Spec\v3\Document;
6
use JsonSchema;
7
use stdClass;
8
use Symfony\Component\Yaml\Yaml;
9
10
/**
11
 * Open API document validator
12
 */
13
class DocumentValidator
14
{
15
    /**
16
     * @var stdClass
17
     */
18
    protected $jsonSchema;
19
20
    /**
21
     * @var string
22
     */
23
    protected $defaultJsonSchemaFile = '/../Spec/v3/schemas/v3.0.x.yml';
24
25
    /**
26
     * @param string $jsonSchema JSON Schema of the Open API specification, in YAML format. If omitted, the bundled
27
     * Open API 3.0.x JSON Schema file will be used.
28
     */
29 12
    public function __construct(string $jsonSchema = null)
30
    {
31 12
        if (is_null($jsonSchema)) {
32 12
            $schemaFile = realpath(__DIR__ . $this->defaultJsonSchemaFile);
33 12
            if (!file_exists($schemaFile)) {
34 3
                throw new \LogicException("The default schema file cannot be found: ${schemaFile}");
35
            }
36 12
            $jsonSchema = file_get_contents($schemaFile);
37
        }
38
39
        $this->jsonSchema = Yaml::parse($jsonSchema, Yaml::PARSE_OBJECT_FOR_MAP);
40
    }
41
42
    /**
43
     * @param Document $document
44
     * @return ValidationResult
45
     */
46
    public function validate(Document $document): ValidationResult
47
    {
48 6
        $documentObject = $document->toObject();
49 6
        $validator      = new JsonSchema\Validator();
50 6
        $validator->validate($documentObject, $this->jsonSchema);
51 6
        return new ValidationResult($validator->getErrors());
52
    }
53
54
    public function getJsonSchema(): stdClass
55
    {
56 3
        return $this->jsonSchema;
57
    }
58
}
59