Passed
Pull Request — master (#19444)
by Fedonyuk
09:17
created

ErrorHandler::handleFatalError()   B

Complexity

Conditions 8
Paths 38

Size

Total Lines 56
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 8
eloc 31
c 3
b 1
f 0
nc 38
nop 0
dl 0
loc 56
ccs 0
cts 31
cp 0
crap 72
rs 8.1795

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use Yii;
11
use yii\helpers\VarDumper;
12
use yii\web\HttpException;
13
14
/**
15
 * ErrorHandler handles uncaught PHP errors and exceptions.
16
 *
17
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
18
 * You can access that instance via `Yii::$app->errorHandler`.
19
 *
20
 * For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @author Alexander Makarov <[email protected]>
24
 * @author Carsten Brandt <[email protected]>
25
 * @since 2.0
26
 */
27
abstract class ErrorHandler extends Component
28
{
29
    /**
30
     * @event Event an event that is triggered when the handler is called by shutdown function via [[handleFatalError()]].
31
     * @since 2.0.46
32
     */
33
    const EVENT_SHUTDOWN = 'shutdown';
34
35
    /**
36
     * @var bool whether to discard any existing page output before error display. Defaults to true.
37
     */
38
    public $discardExistingOutput = true;
39
    /**
40
     * @var int the size of the reserved memory. A portion of memory is pre-allocated so that
41
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
42
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
43
     * Defaults to 256KB.
44
     */
45
    public $memoryReserveSize = 262144;
46
    /**
47
     * @var \Throwable|null the exception that is being handled currently.
48
     */
49
    public $exception;
50
    /**
51
     * @var bool if true - `handleException()` will finish script with `ExitCode::OK`.
52
     * false - `ExitCode::UNSPECIFIED_ERROR`.
53
     * @since 2.0.36
54
     */
55
    public $silentExitOnException;
56
57
    /**
58
     * @var string Used to reserve memory for fatal error handler.
59
     */
60
    private $_memoryReserve;
61
    /**
62
     * @var \Throwable from HHVM error that stores backtrace
63
     */
64
    private $_hhvmException;
65
    /**
66
     * @var bool whether this instance has been registered using `register()`
67
     */
68
    private $_registered = false;
69
    /**
70
     * @var string the current working directory
71
     */
72
    private $_workingDirectory;
73
74
75 243
    public function init()
76
    {
77 243
        $this->silentExitOnException = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST;
78 243
        parent::init();
79 243
    }
80
81
    /**
82
     * Register this error handler.
83
     *
84
     * @since 2.0.32 this will not do anything if the error handler was already registered
85
     */
86
    public function register()
87
    {
88
        if (!$this->_registered) {
89
            ini_set('display_errors', false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $value of ini_set(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

89
            ini_set('display_errors', /** @scrutinizer ignore-type */ false);
Loading history...
90
            set_exception_handler([$this, 'handleException']);
91
            if (defined('HHVM_VERSION')) {
92
                set_error_handler([$this, 'handleHhvmError']);
93
            } else {
94
                set_error_handler([$this, 'handleError']);
95
            }
96
            if ($this->memoryReserveSize > 0) {
97
                $this->_memoryReserve = str_pad('', $this->memoryReserveSize, 'x');
98
            }
99
            // to restore working directory in shutdown handler
100
            if (PHP_SAPI !== 'cli') {
101
                $this->_workingDirectory = getcwd();
102
            }
103
            register_shutdown_function([$this, 'handleFatalError']);
104
            $this->_registered = true;
105
        }
106
    }
107
108
    /**
109
     * Unregisters this error handler by restoring the PHP error and exception handlers.
110
     * @since 2.0.32 this will not do anything if the error handler was not registered
111
     */
112
    public function unregister()
113
    {
114
        if ($this->_registered) {
115
            $this->_memoryReserve = null;
116
            $this->_workingDirectory = null;
117
            restore_error_handler();
118
            restore_exception_handler();
119
            $this->_registered = false;
120
        }
121
    }
122
123
    /**
124
     * Handles uncaught PHP exceptions.
125
     *
126
     * This method is implemented as a PHP exception handler.
127
     *
128
     * @param \Throwable $exception the exception that is not caught
129
     */
130
    public function handleException($exception)
131
    {
132
        if ($exception instanceof ExitException) {
133
            return;
134
        }
135
136
        $this->exception = $exception;
137
138
        // disable error capturing to avoid recursive errors while handling exceptions
139
        $this->unregister();
140
141
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
142
        // HTTP exceptions will override this value in renderException()
143
        if (PHP_SAPI !== 'cli') {
144
            http_response_code(500);
145
        }
146
147
        try {
148
            $this->logException($exception);
149
            if ($this->discardExistingOutput) {
150
                $this->clearOutput();
151
            }
152
            $this->renderException($exception);
153
            if (!$this->silentExitOnException) {
154
                \Yii::getLogger()->flush(true);
155
                if (defined('HHVM_VERSION')) {
156
                    flush();
157
                }
158
                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...
159
            }
160
        } catch (\Exception $e) {
161
            // an other exception could be thrown while displaying the exception
162
            $this->handleFallbackExceptionMessage($e, $exception);
163
        } catch (\Throwable $e) {
164
            // additional check for \Throwable introduced in PHP 7
165
            $this->handleFallbackExceptionMessage($e, $exception);
166
        }
167
168
        $this->exception = null;
169
    }
170
171
    /**
172
     * Handles exception thrown during exception processing in [[handleException()]].
173
     * @param \Throwable $exception Exception that was thrown during main exception processing.
174
     * @param \Throwable $previousException Main exception processed in [[handleException()]].
175
     * @since 2.0.11
176
     */
177
    protected function handleFallbackExceptionMessage($exception, $previousException)
178
    {
179
        $msg = "An Error occurred while handling another error:\n";
180
        $msg .= (string) $exception;
181
        $msg .= "\nPrevious exception:\n";
182
        $msg .= (string) $previousException;
183
        if (YII_DEBUG) {
184
            if (PHP_SAPI === 'cli') {
185
                echo $msg . "\n";
186
            } else {
187
                echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
188
            }
189
            $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
190
        } else {
191
            echo 'An internal server error occurred.';
192
        }
193
        error_log($msg);
194
        if (defined('HHVM_VERSION')) {
195
            flush();
196
        }
197
        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...
198
    }
199
200
    /**
201
     * Handles HHVM execution errors such as warnings and notices.
202
     *
203
     * This method is used as a HHVM error handler. It will store exception that will
204
     * be used in fatal error handler
205
     *
206
     * @param int $code the level of the error raised.
207
     * @param string $message the error message.
208
     * @param string $file the filename that the error was raised in.
209
     * @param int $line the line number the error was raised at.
210
     * @param mixed $context
211
     * @param mixed $backtrace trace of error
212
     * @return bool whether the normal error handler continues.
213
     *
214
     * @throws ErrorException
215
     * @since 2.0.6
216
     */
217
    public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
218
    {
219
        if ($this->handleError($code, $message, $file, $line)) {
220
            return true;
221
        }
222
        if (E_ERROR & $code) {
223
            $exception = new ErrorException($message, $code, $code, $file, $line);
224
            $ref = new \ReflectionProperty('\Exception', 'trace');
225
            $ref->setAccessible(true);
226
            $ref->setValue($exception, $backtrace);
227
            $this->_hhvmException = $exception;
228
        }
229
230
        return false;
231
    }
232
233
    /**
234
     * Handles PHP execution errors such as warnings and notices.
235
     *
236
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
237
     *
238
     * @param int $code the level of the error raised.
239
     * @param string $message the error message.
240
     * @param string $file the filename that the error was raised in.
241
     * @param int $line the line number the error was raised at.
242
     * @return bool whether the normal error handler continues.
243
     *
244
     * @throws ErrorException
245
     */
246
    public function handleError($code, $message, $file, $line)
247
    {
248
        if (error_reporting() & $code) {
249
            // load ErrorException manually here because autoloading them will not work
250
            // when error occurs while autoloading a class
251
            if (!class_exists('yii\\base\\ErrorException', false)) {
252
                require_once __DIR__ . '/ErrorException.php';
253
            }
254
            $exception = new ErrorException($message, $code, $code, $file, $line);
255
256
            if (PHP_VERSION_ID < 70400) {
257
                // prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error
258
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
259
                array_shift($trace);
260
                foreach ($trace as $frame) {
261
                    if ($frame['function'] === '__toString') {
262
                        $this->handleException($exception);
263
                        if (defined('HHVM_VERSION')) {
264
                            flush();
265
                        }
266
                        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...
267
                    }
268
                }
269
            }
270
271
            throw $exception;
272
        }
273
274
        return false;
275
    }
276
277
    /**
278
     * Handles fatal PHP errors.
279
     *
280
     * @return void
281
     */
282
    public function handleFatalError()
283
    {
284
        unset($this->_memoryReserve);
285
286
        if (isset($this->_workingDirectory)) {
287
            // fix working directory for some Web servers e.g. Apache
288
            chdir($this->_workingDirectory);
289
            // flush memory
290
            unset($this->_workingDirectory);
291
        }
292
293
        $error = error_get_last();
294
        if ($error === null) {
295
            return;
296
        }
297
298
        // load ErrorException manually here because autoloading them will not work
299
        // when error occurs while autoloading a class
300
        if (!class_exists('yii\\base\\ErrorException', false)) {
301
            require_once __DIR__ . '/ErrorException.php';
302
        }
303
        if (!ErrorException::isFatalError($error)) {
304
            return;
305
        }
306
307
        if (empty($this->_hhvmException)) {
308
            $this->exception = $this->_hhvmException;
309
        } else {
310
            $this->exception = new ErrorException(
311
                $error['message'],
312
                $error['type'],
313
                $error['type'],
314
                $error['file'],
315
                $error['line']
316
            );
317
        }
318
        unset($error);
319
320
        $this->logException($this->exception);
321
322
        if ($this->discardExistingOutput) {
323
            $this->clearOutput();
324
        }
325
        $this->renderException($this->exception);
326
327
        // need to explicitly flush logs because exit() next will terminate the app immediately
328
        Yii::getLogger()->flush(true);
329
        if (defined('HHVM_VERSION')) {
330
            flush();
331
        }
332
333
        $this->trigger(static::EVENT_SHUTDOWN);
334
335
        // ensure it is called after user-defined shutdown functions
336
        register_shutdown_function(function () {
337
            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...
338
        });
339
    }
340
341
    /**
342
     * Renders the exception.
343
     * @param \Throwable $exception the exception to be rendered.
344
     */
345
    abstract protected function renderException($exception);
346
347
    /**
348
     * Logs the given exception.
349
     * @param \Throwable $exception the exception to be logged
350
     * @since 2.0.3 this method is now public.
351
     */
352
    public function logException($exception)
353
    {
354
        $category = get_class($exception);
355
        if ($exception instanceof HttpException) {
356
            $category = 'yii\\web\\HttpException:' . $exception->statusCode;
357
        } elseif ($exception instanceof \ErrorException) {
358
            $category .= ':' . $exception->getSeverity();
359
        }
360
        Yii::error($exception, $category);
361
    }
362
363
    /**
364
     * Removes all output echoed before calling this method.
365
     */
366
    public function clearOutput()
367
    {
368
        // the following manual level counting is to deal with zlib.output_compression set to On
369
        for ($level = ob_get_level(); $level > 0; --$level) {
370
            if (!@ob_end_clean()) {
371
                ob_clean();
372
            }
373
        }
374
    }
375
376
    /**
377
     * Converts an exception into a PHP error.
378
     *
379
     * This method can be used to convert exceptions inside of methods like `__toString()`
380
     * to PHP errors because exceptions cannot be thrown inside of them.
381
     * @param \Throwable $exception the exception to convert to a PHP error.
382
     * @return never
383
     */
384
    public static function convertExceptionToError($exception)
385
    {
386
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
387
    }
388
389
    /**
390
     * Converts an exception into a simple string.
391
     * @param \Throwable $exception the exception being converted
392
     * @return string the string representation of the exception.
393
     */
394
    public static function convertExceptionToString($exception)
395
    {
396
        if ($exception instanceof UserException) {
397
            return "{$exception->getName()}: {$exception->getMessage()}";
398
        }
399
400
        if (YII_DEBUG) {
401
            return static::convertExceptionToVerboseString($exception);
402
        }
403
404
        return 'An internal server error occurred.';
405
    }
406
407
    /**
408
     * Converts an exception into a string that has verbose information about the exception and its trace.
409
     * @param \Throwable $exception the exception being converted
410
     * @return string the string representation of the exception.
411
     *
412
     * @since 2.0.14
413
     */
414 1
    public static function convertExceptionToVerboseString($exception)
415
    {
416 1
        if ($exception instanceof Exception) {
417
            $message = "Exception ({$exception->getName()})";
418 1
        } elseif ($exception instanceof ErrorException) {
419
            $message = (string)$exception->getName();
420
        } else {
421 1
            $message = 'Exception';
422
        }
423 1
        $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
424 1
            . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
425 1
            . "Stack trace:\n" . $exception->getTraceAsString();
426
427 1
        return $message;
428
    }
429
}
430