Passed
Branch master (31b9e5)
by Tomáš
01:44
created

Handler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 14
c 1
b 0
f 0
dl 0
loc 58
ccs 4
cts 4
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A withErrorHandler() 0 9 1
A withErrorHandlerForDOMDocument() 0 9 2
A withErrorHandlerForXMLReader() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Inspirum\XML\Exception;
6
7
use DOMException;
8
use Exception;
9
use function restore_error_handler;
10
use function set_error_handler;
11
use function strpos;
12
13
final class Handler
14
{
15
    /**
16
     * @param callable(): T $callback
17
     *
18
     * @return T
1 ignored issue
show
Bug introduced by
The type Inspirum\XML\Exception\T was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
     *
20
     * @throws \Exception
21
     *
22
     * @template T
23
     */
24 16
    public static function withErrorHandlerForXMLReader(callable $callback): mixed
25
    {
26 16
        return self::withErrorHandler(static function (int $code, string $message): bool {
27 3
            if (strpos($message, 'XMLReader::') !== false) {
28 3
                throw new Exception($message, $code);
29
            }
30
31
            // @codeCoverageIgnoreStart
32
            return false;
33
            // @codeCoverageIgnoreENd
34
        }, $callback);
35
    }
36
37
    /**
38
     * @param callable(): T $callback
39
     *
40
     * @return T
41
     *
42
     * @throws \DOMException
43
     *
44
     * @template T
45
     */
46
    public static function withErrorHandlerForDOMDocument(callable $callback): mixed
47
    {
48
        return self::withErrorHandler(static function (int $code, string $message): bool {
49
            if (strpos($message, 'DOMDocument::') !== false) {
50
                throw new DOMException($message, $code);
51
            }
52
53
            return false;
54
        }, $callback);
55
    }
56
57
    /**
58
     * Register custom error handler to throw \Exception on warning message
59
     *
60
     * @throws \Exception
61
     */
62
    private static function withErrorHandler(callable $errorCallback, callable $functionCallback): mixed
63
    {
64
        set_error_handler($errorCallback);
65
66
        $response = $functionCallback();
67
68
        restore_error_handler();
69
70
        return $response;
71
    }
72
}
73