1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace XmlSchemaValidator; |
4
|
|
|
|
5
|
|
|
class LibXmlException extends SchemaValidatorException |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Create a LibXmlException based on errors in libxml. |
9
|
|
|
* If found, clear the errors and chain all the error messages. |
10
|
|
|
* |
11
|
|
|
* @return LibXmlException|null |
12
|
|
|
*/ |
13
|
4 |
|
public static function createFromLibXml() |
14
|
|
|
{ |
15
|
4 |
|
$errors = libxml_get_errors(); |
16
|
4 |
|
if (count($errors)) { |
17
|
1 |
|
libxml_clear_errors(); |
18
|
|
|
} |
19
|
4 |
|
$lastException = null; |
20
|
|
|
/** @var \LibXMLError $error */ |
21
|
4 |
|
foreach ($errors as $error) { |
22
|
1 |
|
$current = new self($error->message, 0, $lastException); |
23
|
1 |
|
$lastException = $current; |
24
|
|
|
} |
25
|
4 |
|
if (null !== $lastException) { |
26
|
1 |
|
return $lastException; |
27
|
|
|
} |
28
|
3 |
|
return null; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Throw a LibXmlException based on errors in libxml. |
33
|
|
|
* If found, clear the errors and chain all the error messages. |
34
|
|
|
* |
35
|
|
|
* @throws LibXmlException when found a libxml error |
36
|
|
|
* @return void |
37
|
|
|
*/ |
38
|
3 |
|
public static function throwFromLibXml() |
39
|
|
|
{ |
40
|
3 |
|
$exception = static::createFromLibXml(); |
41
|
3 |
|
if (null !== $exception) { |
42
|
1 |
|
throw $exception; |
43
|
|
|
} |
44
|
2 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Execute a callable ensuring that the execution will occur inside an environment |
48
|
|
|
* where libxml use internal errors is true. |
49
|
|
|
* |
50
|
|
|
* After executing the callable the value of libxml use internal errors is set to |
51
|
|
|
* previous value. |
52
|
|
|
* |
53
|
|
|
* @param callable $callable |
54
|
|
|
* @return mixed |
55
|
|
|
* |
56
|
|
|
* @throws LibXmlException if some error inside libxml was found |
57
|
|
|
*/ |
58
|
3 |
|
public static function useInternalErrors(callable $callable) |
59
|
|
|
{ |
60
|
3 |
|
$previousErrorReporting = error_reporting(); |
61
|
3 |
|
error_reporting(0); |
62
|
3 |
|
$previousLibXmlUseInternalErrors = libxml_use_internal_errors(true); |
63
|
3 |
|
if ($previousLibXmlUseInternalErrors) { |
64
|
1 |
|
libxml_clear_errors(); |
65
|
|
|
} |
66
|
|
|
/** @psalm-var mixed $return */ |
67
|
3 |
|
$return = $callable(); |
68
|
|
|
try { |
69
|
3 |
|
static::throwFromLibXml(); |
70
|
2 |
|
} finally { |
71
|
3 |
|
error_reporting($previousErrorReporting); |
72
|
3 |
|
libxml_use_internal_errors($previousLibXmlUseInternalErrors); |
73
|
|
|
} |
74
|
2 |
|
return $return; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|