Completed
Push — remove-hhvm ( 3f0295 )
by Alexander
13:56 queued 10:07
created

ErrorHandler   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 261
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 36
lcom 2
cbo 7
dl 0
loc 261
ccs 0
cts 103
cp 0
rs 8.8
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 11 2
A unregister() 0 5 1
C handleException() 0 37 7
A handleFallbackExceptionMessage() 0 18 3
B handleError() 0 24 5
B handleFatalError() 0 28 4
renderException() 0 1 ?
A logException() 0 10 3
A clearOutput() 0 9 3
A convertExceptionToError() 0 4 1
B convertExceptionToString() 0 20 7
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
51
    /**
52
     * Register this error handler
53
     */
54
    public function register()
55
    {
56
        ini_set('display_errors', false);
57
        set_exception_handler([$this, 'handleException']);
58
        set_error_handler([$this, 'handleError']);
59
60
        if ($this->memoryReserveSize > 0) {
61
            $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
62
        }
63
        register_shutdown_function([$this, 'handleFatalError']);
64
    }
65
66
    /**
67
     * Unregisters this error handler by restoring the PHP error and exception handlers.
68
     */
69
    public function unregister()
70
    {
71
        restore_error_handler();
72
        restore_exception_handler();
73
    }
74
75
    /**
76
     * Handles uncaught PHP exceptions.
77
     *
78
     * This method is implemented as a PHP exception handler.
79
     *
80
     * @param \Exception $exception the exception that is not caught
81
     */
82
    public function handleException($exception)
83
    {
84
        if ($exception instanceof ExitException) {
85
            return;
86
        }
87
88
        $this->exception = $exception;
89
90
        // disable error capturing to avoid recursive errors while handling exceptions
91
        $this->unregister();
92
93
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
94
        // HTTP exceptions will override this value in renderException()
95
        if (PHP_SAPI !== 'cli') {
96
            http_response_code(500);
97
        }
98
99
        try {
100
            $this->logException($exception);
101
            if ($this->discardExistingOutput) {
102
                $this->clearOutput();
103
            }
104
            $this->renderException($exception);
105
            if (!YII_ENV_TEST) {
106
                \Yii::getLogger()->flush(true);
107
                exit(1);
108
            }
109
        } catch (\Exception $e) {
110
            // an other exception could be thrown while displaying the exception
111
            $this->handleFallbackExceptionMessage($e, $exception);
112
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
113
            // additional check for \Throwable introduced in PHP 7
114
            $this->handleFallbackExceptionMessage($e, $exception);
115
        }
116
117
        $this->exception = null;
118
    }
119
120
    /**
121
     * Handles exception thrown during exception processing in [[handleException()]].
122
     * @param \Exception|\Throwable $exception Exception that was thrown during main exception processing.
123
     * @param \Exception $previousException Main exception processed in [[handleException()]].
124
     * @since 2.0.11
125
     */
126
    protected function handleFallbackExceptionMessage($exception, $previousException) {
127
        $msg = "An Error occurred while handling another error:\n";
128
        $msg .= (string) $exception;
129
        $msg .= "\nPrevious exception:\n";
130
        $msg .= (string) $previousException;
131
        if (YII_DEBUG) {
132
            if (PHP_SAPI === 'cli') {
133
                echo $msg . "\n";
134
            } else {
135
                echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
136
            }
137
        } else {
138
            echo 'An internal server error occurred.';
139
        }
140
        $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
141
        error_log($msg);
142
        exit(1);
143
    }
144
145
    /**
146
     * Handles PHP execution errors such as warnings and notices.
147
     *
148
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
149
     *
150
     * @param int $code the level of the error raised.
151
     * @param string $message the error message.
152
     * @param string $file the filename that the error was raised in.
153
     * @param int $line the line number the error was raised at.
154
     * @return bool whether the normal error handler continues.
155
     *
156
     * @throws ErrorException
157
     */
158
    public function handleError($code, $message, $file, $line)
159
    {
160
        if (error_reporting() & $code) {
161
            // load ErrorException manually here because autoloading them will not work
162
            // when error occurs while autoloading a class
163
            if (!class_exists(ErrorException::class, false)) {
164
                require_once(__DIR__ . '/ErrorException.php');
165
            }
166
            $exception = new ErrorException($message, $code, $code, $file, $line);
167
168
            // in case error appeared in __toString method we can't throw any exception
169
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
170
            array_shift($trace);
171
            foreach ($trace as $frame) {
172
                if ($frame['function'] === '__toString') {
173
                    $this->handleException($exception);
174
                    exit(1);
175
                }
176
            }
177
178
            throw $exception;
179
        }
180
        return false;
181
    }
182
183
    /**
184
     * Handles fatal PHP errors
185
     */
186
    public function handleFatalError()
187
    {
188
        unset($this->_memoryReserve);
189
190
        // load ErrorException manually here because autoloading them will not
191
        // work when error occurs while autoloading a class
192
        if (!class_exists(ErrorException::class, false)) {
193
            require_once(__DIR__ . '/ErrorException.php');
194
        }
195
196
        $error = error_get_last();
197
198
        if (ErrorException::isFatalError($error)) {
199
            $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
200
            $this->exception = $exception;
201
202
            $this->logException($exception);
203
204
            if ($this->discardExistingOutput) {
205
                $this->clearOutput();
206
            }
207
            $this->renderException($exception);
208
209
            // need to explicitly flush logs because exit() next will terminate the app immediately
210
            Yii::getLogger()->flush(true);
211
            exit(1);
212
        }
213
    }
214
215
    /**
216
     * Renders the exception.
217
     * @param \Exception $exception the exception to be rendered.
218
     */
219
    abstract protected function renderException($exception);
220
221
    /**
222
     * Logs the given exception
223
     * @param \Exception $exception the exception to be logged
224
     * @since 2.0.3 this method is now public.
225
     */
226
    public function logException($exception)
227
    {
228
        $category = get_class($exception);
229
        if ($exception instanceof HttpException) {
230
            $category = HttpException::class . ': ' . $exception->statusCode;
231
        } elseif ($exception instanceof \ErrorException) {
232
            $category .= ':' . $exception->getSeverity();
233
        }
234
        Yii::error($exception, $category);
235
    }
236
237
    /**
238
     * Removes all output echoed before calling this method.
239
     */
240
    public function clearOutput()
241
    {
242
        // the following manual level counting is to deal with zlib.output_compression set to On
243
        for ($level = ob_get_level(); $level > 0; --$level) {
244
            if (!@ob_end_clean()) {
245
                ob_clean();
246
            }
247
        }
248
    }
249
250
    /**
251
     * Converts an exception into a PHP error.
252
     *
253
     * This method can be used to convert exceptions inside of methods like `__toString()`
254
     * to PHP errors because exceptions cannot be thrown inside of them.
255
     * @param \Exception $exception the exception to convert to a PHP error.
256
     */
257
    public static function convertExceptionToError($exception)
258
    {
259
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
260
    }
261
262
    /**
263
     * Converts an exception into a simple string.
264
     * @param \Exception|\Error $exception the exception being converted
265
     * @return string the string representation of the exception.
266
     */
267
    public static function convertExceptionToString($exception)
268
    {
269
        if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
270
            $message = "{$exception->getName()}: {$exception->getMessage()}";
271
        } elseif (YII_DEBUG) {
272
            if ($exception instanceof Exception) {
273
                $message = "Exception ({$exception->getName()})";
274
            } elseif ($exception instanceof ErrorException) {
275
                $message = "{$exception->getName()}";
276
            } else {
277
                $message = 'Exception';
278
            }
279
            $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
280
                . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
281
                . "Stack trace:\n" . $exception->getTraceAsString();
282
        } else {
283
            $message = 'Error: ' . $exception->getMessage();
284
        }
285
        return $message;
286
    }
287
}
288