Completed
Push — master ( 993520...f97157 )
by Dawid
06:13
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 1
    public function __construct(string $schemaLocation)
15
    {
16 1
        $this->schemaLocation = $schemaLocation;
17 1
    }
18
19
    /**
20
     * {@inheritdoc}
21
     */
22 1
    public function validate(string $xmlString): ValidationResult
23
    {
24 1
        $validationResult = new ValidationResult();
25 1
        $useInternalErrors = libxml_use_internal_errors();
26
27 1
        libxml_use_internal_errors(true);
28 1
        libxml_clear_errors();
29
30
        try {
31 1
            $doc = new \DOMDocument();
32 1
            $doc->preserveWhiteSpace = true;
33 1
            $doc->formatOutput = true;
34 1
            $doc->recover = true;
35
36 1
            $doc->loadXML($xmlString);
37
38 1
            if ($doc->schemaValidateSource(file_get_contents($this->schemaLocation))) {
39 1
                return $validationResult;
40
            }
41
42
            foreach (libxml_get_errors() as $error) {
43
                $validationResult->addViolation(ValidationViolation::create($error->message, 'line '.$error->line));
44
            }
45
46
            return $validationResult;
47
        } finally {
48 1
            libxml_clear_errors();
49 1
            libxml_use_internal_errors($useInternalErrors);
50
        }
51
    }
52
}
53