Passed
Pull Request — master (#19401)
by Nekrasov
08:35
created

ErrorHandler   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 391
Duplicated Lines 0 %

Test Coverage

Coverage 8.11%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 142
c 3
b 1
f 0
dl 0
loc 391
ccs 12
cts 148
cp 0.0811
rs 7.92
wmc 51

13 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 2
A handleFallbackExceptionMessage() 0 21 4
B handleException() 0 39 8
A handleHhvmError() 0 14 3
A register() 0 19 5
B handleError() 0 29 7
A unregister() 0 8 2
A convertExceptionToString() 0 11 3
B handleFatalError() 0 47 7
A clearOutput() 0 6 3
A convertExceptionToVerboseString() 0 14 3
A logException() 0 9 3
A convertExceptionToError() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like ErrorHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ErrorHandler, and based on these observations, apply Extract Interface, too.

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
    public function handleFatalError()
281
    {
282
        unset($this->_memoryReserve);
283
284
        if (isset($this->_workingDirectory)) {
285
            // fix working directory for some Web servers e.g. Apache
286
            chdir($this->_workingDirectory);
287
            // flush memory
288
            unset($this->_workingDirectory);
289
        }
290
291
        // load ErrorException manually here because autoloading them will not work
292
        // when error occurs while autoloading a class
293
        if (!class_exists('yii\\base\\ErrorException', false)) {
294
            require_once __DIR__ . '/ErrorException.php';
295
        }
296
297
        $error = error_get_last();
298
299
        if (ErrorException::isFatalError($error)) {
300
            if (!empty($this->_hhvmException)) {
301
                $exception = $this->_hhvmException;
302
            } else {
303
                $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
304
            }
305
            $this->exception = $exception;
306
            unset($error);
307
308
            $this->logException($exception);
309
310
            if ($this->discardExistingOutput) {
311
                $this->clearOutput();
312
            }
313
            $this->renderException($exception);
314
            unset($exception);
315
316
            // need to explicitly flush logs because exit() next will terminate the app immediately
317
            Yii::getLogger()->flush(true);
318
            if (defined('HHVM_VERSION')) {
319
                flush();
320
            }
321
322
            $this->trigger(static::EVENT_SHUTDOWN);
323
324
            // ensure it is called after user-defined shutdown functions
325
            register_shutdown_function(function() {
326
                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...
327
            });
328
        }
329
    }
330
331
    /**
332
     * Renders the exception.
333
     * @param \Throwable $exception the exception to be rendered.
334
     */
335
    abstract protected function renderException($exception);
336
337
    /**
338
     * Logs the given exception.
339
     * @param \Throwable $exception the exception to be logged
340
     * @since 2.0.3 this method is now public.
341
     */
342
    public function logException($exception)
343
    {
344
        $category = get_class($exception);
345
        if ($exception instanceof HttpException) {
346
            $category = 'yii\\web\\HttpException:' . $exception->statusCode;
347
        } elseif ($exception instanceof \ErrorException) {
348
            $category .= ':' . $exception->getSeverity();
349
        }
350
        Yii::error($exception, $category);
351
    }
352
353
    /**
354
     * Removes all output echoed before calling this method.
355
     */
356
    public function clearOutput()
357
    {
358
        // the following manual level counting is to deal with zlib.output_compression set to On
359
        for ($level = ob_get_level(); $level > 0; --$level) {
360
            if (!@ob_end_clean()) {
361
                ob_clean();
362
            }
363
        }
364
    }
365
366
    /**
367
     * Converts an exception into a PHP error.
368
     *
369
     * This method can be used to convert exceptions inside of methods like `__toString()`
370
     * to PHP errors because exceptions cannot be thrown inside of them.
371
     * @param \Throwable $exception the exception to convert to a PHP error.
372
     * @return never
373
     */
374
    public static function convertExceptionToError($exception)
375
    {
376
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
377
    }
378
379
    /**
380
     * Converts an exception into a simple string.
381
     * @param \Throwable $exception the exception being converted
382
     * @return string the string representation of the exception.
383
     */
384
    public static function convertExceptionToString($exception)
385
    {
386
        if ($exception instanceof UserException) {
387
            return "{$exception->getName()}: {$exception->getMessage()}";
388
        }
389
390
        if (YII_DEBUG) {
391
            return static::convertExceptionToVerboseString($exception);
392
        }
393
394
        return 'An internal server error occurred.';
395
    }
396
397
    /**
398
     * Converts an exception into a string that has verbose information about the exception and its trace.
399
     * @param \Throwable $exception the exception being converted
400
     * @return string the string representation of the exception.
401
     *
402
     * @since 2.0.14
403
     */
404 1
    public static function convertExceptionToVerboseString($exception)
405
    {
406 1
        if ($exception instanceof Exception) {
407
            $message = "Exception ({$exception->getName()})";
408 1
        } elseif ($exception instanceof ErrorException) {
409
            $message = (string)$exception->getName();
410
        } else {
411 1
            $message = 'Exception';
412
        }
413 1
        $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
414 1
            . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
415 1
            . "Stack trace:\n" . $exception->getTraceAsString();
416
417 1
        return $message;
418
    }
419
}
420