Passed
Push — master ( 7ebbf4...72467b )
by Dmitriy
49s queued 13s
created

ErrorHandler   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 175
Duplicated Lines 0 %

Test Coverage

Coverage 60.32%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 25
eloc 58
c 3
b 0
f 0
dl 0
loc 175
ccs 38
cts 63
cp 0.6032
rs 10

8 Methods

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