Completed
Push — master ( f3053a...8fcbaf )
by Carlos C
03:21
created

LibXmlException::throwFromLibXml()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.7333
c 0
b 0
f 0
cc 4
nc 8
nop 0
crap 4
1
<?php
2
namespace XmlSchemaValidator;
3
4
class LibXmlException extends SchemaValidatorException
5
{
6
    /**
7
     * Checks for errors in libxml, if found clear the errors and chain all the error messages
8
     *
9
     * @throws LibXmlException when found a libxml error
10
     */
11 12
    public static function throwFromLibXml()
12
    {
13 12
        $errors = libxml_get_errors();
14 12
        if (count($errors)) {
15 5
            libxml_clear_errors();
16
        }
17 12
        $lastException = null;
18
        /** @var \LibXMLError $error */
19 12
        foreach ($errors as $error) {
20 5
            $current = new self($error->message, 0, $lastException);
21 5
            $lastException = $current;
22
        }
23 12
        if (null !== $lastException) {
24 5
            throw $lastException;
25
        }
26 11
    }
27
28
    /**
29
     * Execute a callable ensuring that the execution will occur inside an environment
30
     * where libxml use internal errors is true.
31
     *
32
     * After executing the callable the value of libxml use internal errors is set to
33
     * previous value.
34
     *
35
     * @param callable $callable
36
     * @return mixed
37
     *
38
     * @throws LibXmlException if some error inside libxml was found
39
     */
40 12
    public static function useInternalErrors(callable $callable)
41
    {
42 12
        $previousErrorReporting = error_reporting();
43 12
        error_reporting(0);
44 12
        $previousLibXmlUseInternalErrors = libxml_use_internal_errors(true);
45 12
        if ($previousLibXmlUseInternalErrors) {
46
            libxml_clear_errors();
47
        }
48 12
        $return = $callable();
49
        try {
50 12
            static::throwFromLibXml();
51 11
        } finally {
52 12
            error_reporting($previousErrorReporting);
53 12
            libxml_use_internal_errors($previousLibXmlUseInternalErrors);
54
        }
55 11
        return $return;
56
    }
57
}
58