Passed
Push — master ( 27a3a0...89f0ba )
by Dawid
03:11
created

XmlSchemaValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiechu\SymfonyCommonsBundle\Service\SchemaValidator;
6
7
class XmlSchemaValidator implements SchemaValidatorInterface
8
{
9
    /**
10
     * @var string
11
     */
12
    protected $schemaLocation;
13
14 2
    public function __construct(string $schemaLocation)
15
    {
16 2
        $this->schemaLocation = $schemaLocation;
17 2
    }
18
19
    /**
20
     * {@inheritdoc}
21
     */
22 2
    public function validate(string $xmlString): ValidationResult
23
    {
24 2
        $validationResult = new ValidationResult();
25 2
        $useInternalErrors = libxml_use_internal_errors();
26
27 2
        libxml_use_internal_errors(true);
28 2
        libxml_clear_errors();
29
30
        try {
31 2
            $doc = new \DOMDocument();
32 2
            $doc->preserveWhiteSpace = true;
33 2
            $doc->formatOutput = true;
34 2
            $doc->recover = true;
35
36 2
            $doc->loadXML($xmlString);
37
38 2
            if ($doc->schemaValidateSource(file_get_contents($this->schemaLocation))) {
39 1
                return $validationResult;
40
            }
41
42
            /** @var \LibXMLError $error */
43 1
            foreach (libxml_get_errors() as $error) {
44 1
                $validationResult->addViolation(ValidationViolation::create($error->message, 'line '.$error->line));
45
            }
46
47 1
            return $validationResult;
48
        } finally {
49 2
            libxml_clear_errors();
50 2
            libxml_use_internal_errors($useInternalErrors);
51
        }
52
    }
53
}
54