Passed
Push — master ( 97f672...b1ec36 )
by Dawid
02:54
created

XmlSchemaValidator::createDOMDocument()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
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
            $document = $this->createDOMDocument($xmlString);
32
33 2
            if ($document->schemaValidateSource(file_get_contents($this->schemaLocation))) {
34 1
                return $validationResult;
35
            }
36
37
            /** @var \LibXMLError $error */
38 1
            foreach (libxml_get_errors() as $error) {
39 1
                $validationResult->addViolation(ValidationViolation::create($error->message, 'line '.$error->line));
40
            }
41
42 1
            return $validationResult;
43
        } finally {
44 2
            libxml_clear_errors();
45 2
            libxml_use_internal_errors($useInternalErrors);
46
        }
47
    }
48
49
    /**
50
     * @param string $xmlString
51
     *
52
     * @return \DOMDocument
53
     */
54 2
    protected function createDOMDocument(string $xmlString): \DOMDocument
55
    {
56 2
        $document = new \DOMDocument();
57 2
        $document->preserveWhiteSpace = true;
58 2
        $document->formatOutput = true;
59 2
        $document->recover = true;
60
61 2
        $document->loadXML($xmlString);
62
63 2
        return $document;
64
    }
65
}
66