Completed
Push — master ( 78dfd0...3d9a51 )
by Carlos C
01:25
created

LibXmlException::useInternalErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 9
cp 0.8889
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 1
crap 2.0054
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 9
    public static function throwFromLibXml()
12
    {
13 9
        $errors = libxml_get_errors();
14 9
        if (count($errors)) {
15 4
            libxml_clear_errors();
16
        }
17 9
        $lastException = null;
18
        /** @var \LibXMLError $error */
19 9
        foreach ($errors as $error) {
20 4
            $current = new self($error->message, 0, $lastException);
21 4
            $lastException = $current;
22
        }
23 9
        if (null !== $lastException) {
24 4
            throw $lastException;
25
        }
26 8
    }
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 9
    public static function useInternalErrors(callable $callable)
41
    {
42 9
        $previousLibXmlUseInternalErrors = libxml_use_internal_errors(true);
43 9
        if ($previousLibXmlUseInternalErrors) {
44
            libxml_clear_errors();
45
        }
46 9
        $return = $callable();
47
        try {
48 9
            static::throwFromLibXml();
49 8
        } finally {
50 9
            libxml_use_internal_errors($previousLibXmlUseInternalErrors);
51
        }
52 8
        return $return;
53
    }
54
}
55