Passed
Pull Request — 22.0 (#20403)
by Wilmer
08:05 queued 01:55
created

ErrorHandler   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 383
Duplicated Lines 0 %

Test Coverage

Coverage 10.95%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 138
c 2
b 0
f 0
dl 0
loc 383
ccs 15
cts 137
cp 0.1095
rs 8.5599
wmc 48

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