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

XmlSchemaValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 47
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B validate() 0 31 3
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