|
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
|
|
|
|