Passed
Pull Request — master (#36)
by Evgeniy
02:24
created

ErrorHandler::handle()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 8
nop 3
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ErrorHandler;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Log\LoggerInterface;
9
use Throwable;
10
use Yiisoft\ErrorHandler\Exception\ErrorException;
11
use Yiisoft\ErrorHandler\Renderer\PlainTextRenderer;
12
use Yiisoft\Http\Status;
13
14
use function error_get_last;
15
use function error_reporting;
16
use function function_exists;
17
use function ini_set;
18
use function http_response_code;
19
use function register_shutdown_function;
20
use function restore_error_handler;
21
use function restore_exception_handler;
22
use function set_error_handler;
23
use function set_exception_handler;
24
use function str_repeat;
25
26
/**
27
 * ErrorHandler handles out of memory errors, fatals, warnings, notices and exceptions.
28
 */
29
final class ErrorHandler
30
{
31
    /**
32
     * @var int The size of the reserved memory. A portion of memory is pre-allocated so that
33
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
34
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
35
     * Defaults to 256KB.
36
     */
37
    private int $memoryReserveSize = 262_144;
0 ignored issues
show
Bug introduced by
The constant Yiisoft\ErrorHandler\262_144 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
38
    private string $memoryReserve = '';
39
    private bool $debug = false;
40
41
    private LoggerInterface $logger;
42
    private ThrowableRendererInterface $defaultRenderer;
43
44 17
    public function __construct(LoggerInterface $logger, ThrowableRendererInterface $defaultRenderer)
45
    {
46 17
        $this->logger = $logger;
47 17
        $this->defaultRenderer = $defaultRenderer;
48 17
    }
49
50
    /**
51
     * Handles throwable and returns error data.
52
     *
53
     * @param Throwable $t
54
     * @param ThrowableRendererInterface|null $renderer
55
     * @param ServerRequestInterface|null $request
56
     *
57
     * @return ErrorData
58
     */
59 12
    public function handle(Throwable $t,
60
        ThrowableRendererInterface $renderer = null,
61
        ServerRequestInterface $request = null
62
    ): ErrorData {
63 12
        if ($renderer === null) {
64 5
            $renderer = $this->defaultRenderer;
65
        }
66
67
        try {
68 12
            $this->logger->error((string) (new PlainTextRenderer())->renderVerbose($t, $request), ['throwable' => $t]);
69 12
            return $this->debug ? $renderer->renderVerbose($t, $request) : $renderer->render($t, $request);
70 4
        } catch (Throwable $t) {
71 4
            return new ErrorData((string) $t);
72
        }
73
    }
74
75
    /**
76
     * Enables and disables debug mode.
77
     *
78
     * Ensure that is is disabled in production environment since debug mode exposes sensitive details.
79
     *
80
     * @param bool $enable Enable/disable debugging mode.
81
     */
82 2
    public function debug(bool $enable = true): void
83
    {
84 2
        $this->debug = $enable;
85 2
    }
86
87
    /**
88
     * Sets the size of the reserved memory.
89
     *
90
     * @param int $size The size of the reserved memory.
91
     *
92
     * @see $memoryReserveSize
93
     */
94 6
    public function memoryReserveSize(int $size): void
95
    {
96 6
        $this->memoryReserveSize = $size;
97 6
    }
98
99
    /**
100
     * Register this error handler.
101
     */
102 2
    public function register(): void
103
    {
104
        // Disables the display of error.
105 2
        if (function_exists('ini_set')) {
106 2
            ini_set('display_errors', '0');
107
        }
108
109
        // Handles throwable, echo output and exit.
110 2
        set_exception_handler(function (Throwable $t): void {
111
            $this->renderThrowableAndTerminate($t);
112 2
        });
113
114
        // Handles PHP execution errors such as warnings and notices.
115 2
        set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
116 2
            if (!(error_reporting() & $severity)) {
117
                // This error code is not included in error_reporting.
118
                return true;
119
            }
120
121 2
            throw new ErrorException($message, $severity, $severity, $file, $line);
122 2
        });
123
124 2
        if ($this->memoryReserveSize > 0) {
125
            $this->memoryReserve = str_repeat('x', $this->memoryReserveSize);
126
        }
127
128
        // Handles fatal error.
129 2
        register_shutdown_function(function (): void {
130
            $this->memoryReserve = '';
131
            $e = error_get_last();
132
133
            if ($e !== null && ErrorException::isFatalError($e)) {
134
                $error = new ErrorException($e['message'], $e['type'], $e['type'], $e['file'], $e['line']);
135
                $this->renderThrowableAndTerminate($error);
136
            }
137 2
        });
138 2
    }
139
140
    /**
141
     * Unregisters this error handler by restoring the PHP error and exception handlers.
142
     */
143 1
    public function unregister(): void
144
    {
145 1
        restore_error_handler();
146 1
        restore_exception_handler();
147 1
    }
148
149
    /**
150
     * Renders the throwable and terminates the script.
151
     *
152
     * @param Throwable $t
153
     */
154
    private function renderThrowableAndTerminate(Throwable $t): void
155
    {
156
        // disable error capturing to avoid recursive errors while handling exceptions
157
        $this->unregister();
158
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
159
        http_response_code(Status::INTERNAL_SERVER_ERROR);
160
161
        echo $this->handle($t);
162
        exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
163
    }
164
}
165