XmlLoad   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 18
c 1
b 0
f 0
dl 0
loc 33
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 12 2
A validate() 0 17 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Koriym\DataFile;
6
7
use DOMDocument;
8
use Koriym\DataFile\Exception\DataFileException;
9
use Koriym\DataFile\Exception\DataFileNotFoundException;
10
use SimpleXMLElement;
11
12
use function assert;
13
use function file_exists;
14
use function file_get_contents;
15
use function libxml_clear_errors;
16
use function libxml_get_errors;
17
use function libxml_use_internal_errors;
18
use function simplexml_load_string;
19
use function sprintf;
20
use function substr;
21
22
use const LIBXML_ERR_ERROR;
23
use const LIBXML_ERR_FATAL;
24
25
final class XmlLoad
26
{
27
    public function __invoke(string $xmlPath, string $xsdPath): SimpleXMLElement
28
    {
29
        if (! file_exists($xmlPath)) {
30
            throw new DataFileNotFoundException($xmlPath);
31
        }
32
33
        $this->validate($xmlPath, $xsdPath);
34
        $contents = (string) file_get_contents($xmlPath);
35
        $simpleXml = simplexml_load_string($contents);
36
        assert($simpleXml instanceof SimpleXMLElement);
37
38
        return $simpleXml;
39
    }
40
41
    private function validate(string $xmlPath, string $xsdPath): void
42
    {
43
        libxml_use_internal_errors(true);
44
        $dom = new DOMDocument();
45
        $dom->load($xmlPath);
46
        if ($dom->schemaValidate($xsdPath)) {
47
            return;
48
        }
49
50
        $errors = libxml_get_errors();
51
        foreach ($errors as $error) {
52
            if ($error->level === LIBXML_ERR_FATAL || $error->level === LIBXML_ERR_ERROR) {
53
                libxml_clear_errors();
54
55
                $msg = sprintf('%s in %s:%s', substr($error->message, 0, -2), $error->file, $error->line);
56
57
                throw new DataFileException($msg);
58
                // @codeCoverageIgnoreStart
59
            }
60
        }
61
    }
62
63
    // @codeCoverageIgnoreEnd
64
}
65