Test Failed
Push — master ( 78ef9f...88ea0f )
by Roberto
03:12 queued 11s
created

JsonValidation::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.2408
c 0
b 0
f 0
cc 5
nc 4
nop 3
1
<?php
2
3
namespace NFePHP\eSocial\Common;
4
5
use JsonSchema\Constraints\Constraint;
6
use JsonSchema\Constraints\Factory;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, NFePHP\eSocial\Common\Factory.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use JsonSchema\SchemaStorage;
8
use JsonSchema\Validator;
9
use NFePHP\eSocial\Common\TranslateJsonValidation;
10
11
class JsonValidation
12
{
13
    public static function validate(
14
        \stdClass $std,
15
        string $jsonschema,
16
        string $definitions
17
    ) {
18
        if (!is_file($jsonschema) || !is_file($definitions)) {
19
            return [];
20
        }
21
        $jsonSchemaObject = json_decode((string)file_get_contents($jsonschema));
22
        $schemaStorage = new SchemaStorage();
23
        $schemaStorage->addSchema("file:{$definitions}", $jsonSchemaObject);
24
        $jsonValidator = new Validator(new Factory($schemaStorage));
25
        $jsonValidator->validate($std, $jsonSchemaObject, Constraint::CHECK_MODE_COERCE_TYPES);
26
        if ($jsonValidator->isValid()) {
27
            return [];
28
        }
29
        $resp = [];
30
        foreach ($jsonValidator->getErrors() as $error) {
31
            $error['message'] = TranslateJsonValidation::translate($error['message']);
32
            $resp[] = $error;
33
        }
34
        return $resp;
35
    }
36
}
37