1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Hyperized\Xml; |
4
|
|
|
|
5
|
|
|
use Hyperized\Xml\Constants\Strings; |
6
|
|
|
use Hyperized\Xml\Exceptions\InvalidXmlException; |
7
|
|
|
use Hyperized\Xml\Constants\ErrorMessages; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class Validator |
11
|
|
|
* @package Hyperized\Xml |
12
|
|
|
* Based on: http://stackoverflow.com/a/30058598/1757763 |
13
|
|
|
*/ |
14
|
|
|
final class Validator |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @param $xmlFilename |
18
|
|
|
* @param $xsdFile |
19
|
|
|
* @param string $version |
20
|
|
|
* @param string $encoding |
21
|
|
|
* |
22
|
|
|
* @return bool |
23
|
|
|
* @throws InvalidXmlException |
24
|
|
|
*/ |
25
|
8 |
|
public function isXMLFileValid(string $xmlFilename, string $xsdFile = null, string $version = Strings::version, string $encoding = Strings::UTF8): bool |
26
|
|
|
{ |
27
|
8 |
|
return $this->isXMLStringValid(file_get_contents($xmlFilename), $xsdFile, $version, $encoding); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param $xml |
32
|
|
|
* @param $xsdFile |
33
|
|
|
* @param string $version |
34
|
|
|
* @param string $encoding |
35
|
|
|
* |
36
|
|
|
* @return bool |
37
|
|
|
* @throws InvalidXmlException |
38
|
|
|
*/ |
39
|
14 |
|
public function isXMLStringValid(string $xml, string $xsdFile = null, string $version = Strings::version, string $encoding = Strings::UTF8): bool |
40
|
|
|
{ |
41
|
14 |
|
if ($xsdFile !== null) { |
42
|
4 |
|
return $this->isXMLContentValid($xml, $version, $encoding, $xsdFile); |
43
|
|
|
} |
44
|
10 |
|
return $this->isXMLContentValid($xml, $version, $encoding); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string $xmlContent |
49
|
|
|
* @param string $version |
50
|
|
|
* @param string $encoding |
51
|
|
|
* @param string|null $xsdFile |
52
|
|
|
* |
53
|
|
|
* @return bool |
54
|
|
|
* @throws InvalidXmlException |
55
|
|
|
*/ |
56
|
14 |
|
private function isXMLContentValid(string $xmlContent, string $version = Strings::version, string $encoding = Strings::UTF8, string $xsdFile = null): bool |
57
|
|
|
{ |
58
|
14 |
|
if (trim($xmlContent) === '') { |
59
|
2 |
|
throw new InvalidXmlException(ErrorMessages::XmlEmptyTrimmed); |
60
|
|
|
} |
61
|
|
|
|
62
|
12 |
|
libxml_use_internal_errors(true); |
63
|
|
|
|
64
|
12 |
|
$doc = new \DOMDocument($version, $encoding); |
65
|
12 |
|
$doc->loadXML($xmlContent); |
66
|
12 |
|
if ($xsdFile !== null) { |
67
|
4 |
|
$doc->schemaValidate($xsdFile); |
68
|
|
|
} |
69
|
|
|
|
70
|
12 |
|
$errors = libxml_get_errors(); |
71
|
12 |
|
libxml_clear_errors(); |
72
|
12 |
|
if(!empty($errors)) |
73
|
|
|
{ |
74
|
6 |
|
$return = []; |
75
|
6 |
|
foreach ($errors as $error) { |
76
|
6 |
|
$return[] = trim($error->message); |
77
|
|
|
} |
78
|
6 |
|
throw new InvalidXmlException(implode(Strings::newLine, $return)); |
79
|
|
|
} |
80
|
6 |
|
return true; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|