Completed
Push — php7-travis-apcu ( 9bbcee...fd63c3 )
by Alexander
14:47
created

ErrorHandler::handleHhvmError()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 6
crap 12
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
     * @var bool whether to discard any existing page output before error display. Defaults to true.
31
     */
32
    public $discardExistingOutput = true;
33
    /**
34
     * @var int the size of the reserved memory. A portion of memory is pre-allocated so that
35
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
36
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
37
     * Defaults to 256KB.
38
     */
39
    public $memoryReserveSize = 262144;
40
    /**
41
     * @var \Exception|null the exception that is being handled currently.
42
     */
43
    public $exception;
44
45
    /**
46
     * @var string Used to reserve memory for fatal error handler.
47
     */
48
    private $_memoryReserve;
49
    /**
50
     * @var \Exception from HHVM error that stores backtrace
51
     */
52
    private $_hhvmException;
53
54
55
    /**
56
     * Register this error handler
57
     */
58
    public function register()
59
    {
60
        ini_set('display_errors', false);
61
        set_exception_handler([$this, 'handleException']);
62
        if (defined('HHVM_VERSION')) {
63
            set_error_handler([$this, 'handleHhvmError']);
64
        } else {
65
            set_error_handler([$this, 'handleError']);
66
        }
67
        if ($this->memoryReserveSize > 0) {
68
            $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
69
        }
70
        register_shutdown_function([$this, 'handleFatalError']);
71
    }
72
73
    /**
74
     * Unregisters this error handler by restoring the PHP error and exception handlers.
75
     */
76
    public function unregister()
77
    {
78
        restore_error_handler();
79
        restore_exception_handler();
80
    }
81
82
    /**
83
     * Handles uncaught PHP exceptions.
84
     *
85
     * This method is implemented as a PHP exception handler.
86
     *
87
     * @param \Exception $exception the exception that is not caught
88
     */
89
    public function handleException($exception)
90
    {
91
        if ($exception instanceof ExitException) {
92
            return;
93
        }
94
95
        $this->exception = $exception;
96
97
        // disable error capturing to avoid recursive errors while handling exceptions
98
        $this->unregister();
99
100
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
101
        // HTTP exceptions will override this value in renderException()
102
        if (PHP_SAPI !== 'cli') {
103
            http_response_code(500);
104
        }
105
106
        try {
107
            $this->logException($exception);
108
            if ($this->discardExistingOutput) {
109
                $this->clearOutput();
110
            }
111
            $this->renderException($exception);
112
            if (!YII_ENV_TEST) {
113
                \Yii::getLogger()->flush(true);
114
                if (defined('HHVM_VERSION')) {
115
                    flush();
116
                }
117
                exit(1);
118
            }
119
        } catch (\Throwable $e) {
120
            // another exception could be thrown while displaying the exception
121
            $this->handleFallbackExceptionMessage($e, $exception);
122
        }
123
124
        $this->exception = null;
125
    }
126
127
    /**
128
     * Handles exception thrown during exception processing in [[handleException()]].
129
     * @param \Throwable $exception Exception that was thrown during main exception processing.
130
     * @param \Exception $previousException Main exception processed in [[handleException()]].
131
     * @since 2.0.11
132
     */
133
    protected function handleFallbackExceptionMessage($exception, $previousException)
134
    {
135
        $msg = "An Error occurred while handling another error:\n";
136
        $msg .= (string) $exception;
137
        $msg .= "\nPrevious exception:\n";
138
        $msg .= (string) $previousException;
139
        if (YII_DEBUG) {
140
            if (PHP_SAPI === 'cli') {
141
                echo $msg . "\n";
142
            } else {
143
                echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
144
            }
145
        } else {
146
            echo 'An internal server error occurred.';
147
        }
148
        $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
149
        error_log($msg);
150
        if (defined('HHVM_VERSION')) {
151
            flush();
152
        }
153
        exit(1);
154
    }
155
156
    /**
157
     * Handles HHVM execution errors such as warnings and notices.
158
     *
159
     * This method is used as a HHVM error handler. It will store exception that will
160
     * be used in fatal error handler
161
     *
162
     * @param int $code the level of the error raised.
163
     * @param string $message the error message.
164
     * @param string $file the filename that the error was raised in.
165
     * @param int $line the line number the error was raised at.
166
     * @param mixed $context
167
     * @param mixed $backtrace trace of error
168
     * @return bool whether the normal error handler continues.
169
     *
170
     * @throws ErrorException
171
     * @since 2.0.6
172
     */
173
    public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
174
    {
175
        if ($this->handleError($code, $message, $file, $line)) {
176
            return true;
177
        }
178
        if (E_ERROR & $code) {
179
            $exception = new ErrorException($message, $code, $code, $file, $line);
180
            $ref = new \ReflectionProperty('\Exception', 'trace');
181
            $ref->setAccessible(true);
182
            $ref->setValue($exception, $backtrace);
183
            $this->_hhvmException = $exception;
184
        }
185
        return false;
186
    }
187
188
    /**
189
     * Handles PHP execution errors such as warnings and notices.
190
     *
191
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
192
     *
193
     * @param int $code the level of the error raised.
194
     * @param string $message the error message.
195
     * @param string $file the filename that the error was raised in.
196
     * @param int $line the line number the error was raised at.
197
     * @return bool whether the normal error handler continues.
198
     *
199
     * @throws ErrorException
200
     */
201
    public function handleError($code, $message, $file, $line)
202
    {
203
        if (error_reporting() & $code) {
204
            // load ErrorException manually here because autoloading them will not work
205
            // when error occurs while autoloading a class
206
            if (!class_exists(ErrorException::class, false)) {
207
                require_once __DIR__ . '/ErrorException.php';
208
            }
209
            $exception = new ErrorException($message, $code, $code, $file, $line);
210
211
            // in case error appeared in __toString method we can't throw any exception
212
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
213
            array_shift($trace);
214
            foreach ($trace as $frame) {
215
                if ($frame['function'] === '__toString') {
216
                    $this->handleException($exception);
217
                    if (defined('HHVM_VERSION')) {
218
                        flush();
219
                    }
220
                    exit(1);
221
                }
222
            }
223
224
            throw $exception;
225
        }
226
        return false;
227
    }
228
229
    /**
230
     * Handles fatal PHP errors
231
     */
232
    public function handleFatalError()
233
    {
234
        unset($this->_memoryReserve);
235
236
        // load ErrorException manually here because autoloading them will not work
237
        // when error occurs while autoloading a class
238
        if (!class_exists(ErrorException::class, false)) {
239
            require_once __DIR__ . '/ErrorException.php';
240
        }
241
242
        $error = error_get_last();
243
244
        if (ErrorException::isFatalError($error)) {
245
            if (!empty($this->_hhvmException)) {
246
                $exception = $this->_hhvmException;
247
            } else {
248
                $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
249
            }
250
            $this->exception = $exception;
251
252
            $this->logException($exception);
253
254
            if ($this->discardExistingOutput) {
255
                $this->clearOutput();
256
            }
257
            $this->renderException($exception);
258
259
            // need to explicitly flush logs because exit() next will terminate the app immediately
260
            Yii::getLogger()->flush(true);
261
            if (defined('HHVM_VERSION')) {
262
                flush();
263
            }
264
            exit(1);
265
        }
266
    }
267
268
    /**
269
     * Renders the exception.
270
     * @param \Exception $exception the exception to be rendered.
271
     */
272
    abstract protected function renderException($exception);
273
274
    /**
275
     * Logs the given exception
276
     * @param \Exception $exception the exception to be logged
277
     * @since 2.0.3 this method is now public.
278
     */
279
    public function logException($exception)
280
    {
281
        $category = get_class($exception);
282
        if ($exception instanceof HttpException) {
283
            $category = HttpException::class . ': ' . $exception->statusCode;
284
        } elseif ($exception instanceof \ErrorException) {
0 ignored issues
show
Bug introduced by
The class ErrorException does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
285
            $category .= ':' . $exception->getSeverity();
286
        }
287
        Yii::error($exception, $category);
288
    }
289
290
    /**
291
     * Removes all output echoed before calling this method.
292
     */
293
    public function clearOutput()
294
    {
295
        // the following manual level counting is to deal with zlib.output_compression set to On
296
        for ($level = ob_get_level(); $level > 0; --$level) {
297
            if (!@ob_end_clean()) {
298
                ob_clean();
299
            }
300
        }
301
    }
302
303
    /**
304
     * Converts an exception into a PHP error.
305
     *
306
     * This method can be used to convert exceptions inside of methods like `__toString()`
307
     * to PHP errors because exceptions cannot be thrown inside of them.
308
     * @param \Exception $exception the exception to convert to a PHP error.
309
     */
310
    public static function convertExceptionToError($exception)
311
    {
312
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
313
    }
314
315
    /**
316
     * Converts an exception into a simple string.
317
     * @param \Exception|\Error $exception the exception being converted
318
     * @return string the string representation of the exception.
319
     */
320
    public static function convertExceptionToString($exception)
321
    {
322
        if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
323
            $message = "{$exception->getName()}: {$exception->getMessage()}";
324
        } elseif (YII_DEBUG) {
325
            if ($exception instanceof Exception) {
326
                $message = "Exception ({$exception->getName()})";
327
            } elseif ($exception instanceof ErrorException) {
328
                $message = "{$exception->getName()}";
0 ignored issues
show
Bug introduced by
Consider using $exception->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
329
            } else {
330
                $message = 'Exception';
331
            }
332
            $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
333
                . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
334
                . "Stack trace:\n" . $exception->getTraceAsString();
335
        } else {
336
            $message = 'Error: ' . $exception->getMessage();
337
        }
338
        return $message;
339
    }
340
}
341