Completed
Push — master ( 993520...f97157 )
by Dawid
06:13
created

XmlSchemaValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 85%

Importance

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

2 Methods

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