DocumentValidator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 14
c 2
b 0
f 1
dl 0
loc 44
rs 10
ccs 11
cts 11
cp 1
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 6 1
A getJsonSchema() 0 3 1
A __construct() 0 11 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