Passed
Push — master ( 0b616a...1a71a8 )
by Sergei
02:12
created

ErrorHandler::handle()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 10
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\EventDispatcher\EventDispatcherInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Log\LoggerInterface;
10
use Throwable;
11
use Yiisoft\ErrorHandler\Event\ApplicationError;
12
use Yiisoft\ErrorHandler\Exception\ErrorException;
13
use Yiisoft\ErrorHandler\Renderer\PlainTextRenderer;
14
use Yiisoft\Http\Status;
15
16
use function error_get_last;
17
use function error_reporting;
18
use function function_exists;
19
use function ini_set;
20
use function http_response_code;
21
use function register_shutdown_function;
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
    private ?string $workingDirectory = null;
41
    private bool $enabled = false;
42
    private bool $initialized = false;
43
44
    private LoggerInterface $logger;
45
    private ThrowableRendererInterface $defaultRenderer;
46
    private ?EventDispatcherInterface $eventDispatcher;
47
48 17
    public function __construct(
49
        LoggerInterface $logger,
50
        ThrowableRendererInterface $defaultRenderer,
51
        EventDispatcherInterface $eventDispatcher = null
52
    ) {
53 17
        $this->logger = $logger;
54 17
        $this->defaultRenderer = $defaultRenderer;
55 17
        $this->eventDispatcher = $eventDispatcher;
56
    }
57
58
    /**
59
     * Handles throwable and returns error data.
60
     *
61
     * @param Throwable $t
62
     * @param ThrowableRendererInterface|null $renderer
63
     * @param ServerRequestInterface|null $request
64
     *
65
     * @return ErrorData
66
     */
67 12
    public function handle(
68
        Throwable $t,
69
        ThrowableRendererInterface $renderer = null,
70
        ServerRequestInterface $request = null
71
    ): ErrorData {
72 12
        if ($renderer === null) {
73 5
            $renderer = $this->defaultRenderer;
74
        }
75
76
        try {
77 12
            $this->logger->error((string) (new PlainTextRenderer())->renderVerbose($t, $request), ['throwable' => $t]);
78 12
            return $this->debug ? $renderer->renderVerbose($t, $request) : $renderer->render($t, $request);
79 4
        } catch (Throwable $t) {
80 4
            return new ErrorData((string) $t);
81
        }
82
    }
83
84
    /**
85
     * Enables and disables debug mode.
86
     *
87
     * Ensure that is is disabled in production environment since debug mode exposes sensitive details.
88
     *
89
     * @param bool $enable Enable/disable debugging mode.
90
     */
91 2
    public function debug(bool $enable = true): void
92
    {
93 2
        $this->debug = $enable;
94
    }
95
96
    /**
97
     * Sets the size of the reserved memory.
98
     *
99
     * @param int $size The size of the reserved memory.
100
     *
101
     * @see $memoryReserveSize
102
     */
103 6
    public function memoryReserveSize(int $size): void
104
    {
105 6
        $this->memoryReserveSize = $size;
106
    }
107
108
    /**
109
     * Register PHP exception and error handlers and enable this error handler.
110
     */
111 3
    public function register(): void
112
    {
113 2
        if ($this->enabled) {
114
            return;
115
        }
116
117 2
        if ($this->memoryReserveSize > 0) {
118
            $this->memoryReserve = str_repeat('x', $this->memoryReserveSize);
119
        }
120
121 2
        $this->initializeOnce();
122
123
        // Handles throwable, echo output and exit.
124 2
        set_exception_handler(function (Throwable $t): void {
125
            if (!$this->enabled) {
126
                return;
127
            }
128
129
            $this->renderThrowableAndTerminate($t);
130 2
        });
131
132
        // Handles PHP execution errors such as warnings and notices.
133 2
        set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
134 3
            if (!$this->enabled) {
135 1
                return false;
136
            }
137
138 2
            if (!(error_reporting() & $severity)) {
139
                // This error code is not included in error_reporting.
140
                return true;
141
            }
142
143 2
            throw new ErrorException($message, $severity, $severity, $file, $line);
144 2
        });
145
146 2
        $this->enabled = true;
147
    }
148
149
    /**
150
     * Disable this error handler.
151
     */
152 1
    public function unregister(): void
153
    {
154 1
        if (!$this->enabled) {
155
            return;
156
        }
157
158 1
        $this->memoryReserve = '';
159
160 1
        $this->enabled = false;
161
    }
162
163 2
    private function initializeOnce(): void
164
    {
165 2
        if ($this->initialized) {
166
            return;
167
        }
168
169
        // Disables the display of error.
170 2
        if (function_exists('ini_set')) {
171 2
            ini_set('display_errors', '0');
172
        }
173
174
        // Handles fatal error.
175 2
        register_shutdown_function(function (): void {
176
            if (!$this->enabled) {
177
                return;
178
            }
179
180
            $this->memoryReserve = '';
181
            $e = error_get_last();
182
183
            if ($e !== null && ErrorException::isFatalError($e)) {
184
                $error = new ErrorException($e['message'], $e['type'], $e['type'], $e['file'], $e['line']);
185
                $this->renderThrowableAndTerminate($error);
186
            }
187 2
        });
188
189 2
        if (!(PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg')) {
190
            $this->workingDirectory = getcwd();
191
        }
192
193 2
        $this->initialized = true;
194
    }
195
196
    /**
197
     * Renders the throwable and terminates the script.
198
     *
199
     * @param Throwable $t
200
     */
201
    private function renderThrowableAndTerminate(Throwable $t): void
202
    {
203
        if (!empty($this->workingDirectory)) {
204
            chdir($this->workingDirectory);
205
        }
206
        // disable error capturing to avoid recursive errors while handling exceptions
207
        $this->unregister();
208
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
209
        http_response_code(Status::INTERNAL_SERVER_ERROR);
210
211
        echo $this->handle($t);
212
        if ($this->eventDispatcher !== null) {
213
            $this->eventDispatcher->dispatch(new ApplicationError($t));
214
        }
215
216
        register_shutdown_function(static function (): void {
217
            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...
218
        });
219
    }
220
}
221