Total Complexity | 9 |
Total Lines | 65 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
1 | <?php |
||
10 | class Xml |
||
11 | { |
||
12 | /** |
||
13 | * @param $xml |
||
14 | * @param $schema |
||
15 | * |
||
16 | * @throws \Exception |
||
17 | */ |
||
18 | public static function validate($xml, $schema) |
||
19 | { |
||
20 | libxml_use_internal_errors(true); |
||
21 | $xmlDocument = new \DOMDocument(); |
||
22 | $xmlDocument->loadXML($xml); |
||
23 | |||
24 | $schema = static::prepareSchema($schema); |
||
25 | |||
26 | if (!$xmlDocument->schemaValidateSource($schema)) { |
||
|
|||
27 | $errors = libxml_get_errors(); |
||
28 | |||
29 | foreach ($errors as $error) { |
||
30 | throw new \Exception(static::displayError($error)); |
||
31 | } |
||
32 | libxml_clear_errors(); |
||
33 | throw new \Exception('INVALID XML'); |
||
34 | } |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @param $error |
||
39 | * |
||
40 | * @return string |
||
41 | */ |
||
42 | public static function displayError($error): string |
||
43 | { |
||
44 | $return = "\n"; |
||
45 | switch ($error->level) { |
||
46 | case LIBXML_ERR_WARNING: |
||
47 | $return .= "Warning $error->code: "; |
||
48 | break; |
||
49 | case LIBXML_ERR_ERROR: |
||
50 | $return .= "Error $error->code: "; |
||
51 | break; |
||
52 | case LIBXML_ERR_FATAL: |
||
53 | $return .= "Fatal Error $error->code: "; |
||
54 | break; |
||
55 | } |
||
56 | $return .= trim($error->message); |
||
57 | $return .= "\n"; |
||
58 | |||
59 | return $return; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * @param $schema |
||
64 | * |
||
65 | * @return false|string |
||
66 | */ |
||
67 | protected static function prepareSchema($schema) |
||
75 | } |
||
76 | } |