Completed
Push — master ( 8cd9ee...31bb4c )
by Carlos C
02:12
created

LibXmlException::createFromLibXml()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.7691

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 16
ccs 7
cts 11
cp 0.6364
rs 9.9332
cc 4
nc 8
nop 0
crap 4.7691
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 3
    public static function createFromLibXml()
14
    {
15 3
        $errors = libxml_get_errors();
16 3
        if (count($errors)) {
17
            libxml_clear_errors();
18
        }
19 3
        $lastException = null;
20
        /** @var \LibXMLError $error */
21 3
        foreach ($errors as $error) {
22
            $current = new self($error->message, 0, $lastException);
23
            $lastException = $current;
24
        }
25 3
        if (null !== $lastException) {
26
            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 2
    public static function throwFromLibXml()
39
    {
40 2
        $exception = static::createFromLibXml();
41 2
        if (null !== $exception) {
42
            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 2
    public static function useInternalErrors(callable $callable)
59
    {
60 2
        $previousErrorReporting = error_reporting();
61 2
        error_reporting(0);
62 2
        $previousLibXmlUseInternalErrors = libxml_use_internal_errors(true);
63 2
        if ($previousLibXmlUseInternalErrors) {
64
            libxml_clear_errors();
65
        }
66
        /** @psalm-var mixed $return */
67 2
        $return = $callable();
68
        try {
69 2
            static::throwFromLibXml();
70 2
        } finally {
71 2
            error_reporting($previousErrorReporting);
72 2
            libxml_use_internal_errors($previousLibXmlUseInternalErrors);
73
        }
74 2
        return $return;
75
    }
76
}
77