Completed
Push — 2.1 ( c952e8...98ed49 )
by Carsten
10:00
created

ErrorHandler::argumentsToString()   C

Complexity

Conditions 14
Paths 30

Size

Total Lines 48
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 5.0498
c 0
b 0
f 0
ccs 0
cts 44
cp 0
cc 14
eloc 36
nc 30
nop 1
crap 210

How to fix   Complexity   

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\web;
9
10
use Yii;
11
use yii\base\Exception;
12
use yii\base\ErrorException;
13
use yii\base\UserException;
14
use yii\helpers\VarDumper;
15
16
/**
17
 * ErrorHandler handles uncaught PHP errors and exceptions.
18
 *
19
 * ErrorHandler displays these errors using appropriate views based on the
20
 * nature of the errors and the mode the application runs at.
21
 *
22
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
23
 * You can access that instance via `Yii::$app->errorHandler`.
24
 *
25
 * @author Qiang Xue <[email protected]>
26
 * @author Timur Ruziev <[email protected]>
27
 * @since 2.0
28
 */
29
class ErrorHandler extends \yii\base\ErrorHandler
30
{
31
    /**
32
     * @var integer maximum number of source code lines to be displayed. Defaults to 19.
33
     */
34
    public $maxSourceLines = 19;
35
    /**
36
     * @var integer maximum number of trace source code lines to be displayed. Defaults to 13.
37
     */
38
    public $maxTraceSourceLines = 13;
39
    /**
40
     * @var string the route (e.g. 'site/error') to the controller action that will be used
41
     * to display external errors. Inside the action, it can retrieve the error information
42
     * using `Yii::$app->errorHandler->exception. This property defaults to null, meaning ErrorHandler
43
     * will handle the error display.
44
     */
45
    public $errorAction;
46
    /**
47
     * @var string the path of the view file for rendering exceptions without call stack information.
48
     */
49
    public $errorView = '@yii/views/errorHandler/error.php';
50
    /**
51
     * @var string the path of the view file for rendering exceptions.
52
     */
53
    public $exceptionView = '@yii/views/errorHandler/exception.php';
54
    /**
55
     * @var string the path of the view file for rendering exceptions and errors call stack element.
56
     */
57
    public $callStackItemView = '@yii/views/errorHandler/callStackItem.php';
58
    /**
59
     * @var string the path of the view file for rendering previous exceptions.
60
     */
61
    public $previousExceptionView = '@yii/views/errorHandler/previousException.php';
62
    /**
63
     * @var array list of the PHP predefined variables that should be displayed on the error page.
64
     * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be displayed.
65
     * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION']`.
66
     * @see renderRequest()
67
     * @since 2.0.7
68
     */
69
    public $displayVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION'];
70
71
72
    /**
73
     * Renders the exception.
74
     * @param \Exception $exception the exception to be rendered.
75
     */
76
    protected function renderException($exception)
77
    {
78
        if (Yii::$app->has('response')) {
79
            $response = Yii::$app->getResponse();
80
            // reset parameters of response to avoid interference with partially created response data
81
            // in case the error occurred while sending the response.
82
            $response->isSent = false;
83
            $response->stream = null;
84
            $response->data = null;
85
            $response->content = null;
86
        } else {
87
            $response = new Response();
88
        }
89
90
        $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
91
92
        if ($useErrorView && $this->errorAction !== null) {
93
            $result = Yii::$app->runAction($this->errorAction);
94
            if ($result instanceof Response) {
95
                $response = $result;
96
            } else {
97
                $response->data = $result;
98
            }
99
        } elseif ($response->format === Response::FORMAT_HTML) {
100
            if (YII_ENV_TEST || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
101
                // AJAX request
102
                $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>';
103
            } else {
104
                // if there is an error during error rendering it's useful to
105
                // display PHP error in debug mode instead of a blank screen
106
                if (YII_DEBUG) {
107
                    ini_set('display_errors', 1);
108
                }
109
                $file = $useErrorView ? $this->errorView : $this->exceptionView;
110
                $response->data = $this->renderFile($file, [
111
                    'exception' => $exception,
112
                ]);
113
            }
114
        } elseif ($response->format === Response::FORMAT_RAW) {
115
            $response->data = static::convertExceptionToString($exception);
116
        } else {
117
            $response->data = $this->convertExceptionToArray($exception);
118
        }
119
120
        if ($exception instanceof HttpException) {
121
            $response->setStatusCode($exception->statusCode);
122
        } else {
123
            $response->setStatusCode(500);
124
        }
125
126
        $response->send();
127
    }
128
129
    /**
130
     * Converts an exception into an array.
131
     * @param \Exception $exception the exception being converted
132
     * @return array the array representation of the exception.
133
     */
134
    protected function convertExceptionToArray($exception)
135
    {
136
        if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) {
137
            $exception = new HttpException(500, Yii::t('yii', 'An internal server error occurred.'));
138
        }
139
140
        $array = [
141
            'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',
142
            'message' => $exception->getMessage(),
143
            'code' => $exception->getCode(),
144
        ];
145
        if ($exception instanceof HttpException) {
146
            $array['status'] = $exception->statusCode;
147
        }
148
        if (YII_DEBUG) {
149
            $array['type'] = get_class($exception);
150
            if (!$exception instanceof UserException) {
151
                $array['file'] = $exception->getFile();
152
                $array['line'] = $exception->getLine();
153
                $array['stack-trace'] = explode("\n", $exception->getTraceAsString());
154
                if ($exception instanceof \yii\db\Exception) {
155
                    $array['error-info'] = $exception->errorInfo;
156
                }
157
            }
158
        }
159
        if (($prev = $exception->getPrevious()) !== null) {
160
            $array['previous'] = $this->convertExceptionToArray($prev);
161
        }
162
163
        return $array;
164
    }
165
166
    /**
167
     * Converts special characters to HTML entities.
168
     * @param string $text to encode.
169
     * @return string encoded original text.
170
     */
171
    public function htmlEncode($text)
172
    {
173
        return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
174
    }
175
176
    /**
177
     * Adds informational links to the given PHP type/class.
178
     * @param string $code type/class name to be linkified.
179
     * @return string linkified with HTML type/class name.
180
     */
181
    public function addTypeLinks($code)
182
    {
183
        if (preg_match('/(.*?)::([^(]+)/', $code, $matches)) {
184
            $class = $matches[1];
185
            $method = $matches[2];
186
            $text = $this->htmlEncode($class) . '::' . $this->htmlEncode($method);
187
        } else {
188
            $class = $code;
189
            $method = null;
190
            $text = $this->htmlEncode($class);
191
        }
192
193
        $url = $this->getTypeUrl($class, $method);
194
195
        if (!$url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
196
            return $text;
197
        }
198
199
        return '<a href="' . $url . '" target="_blank">' . $text . '</a>';
200
    }
201
202
    /**
203
     * Returns the informational link URL for a given PHP type/class.
204
     * @param string $class the type or class name.
205
     * @param string|null $method the method name.
206
     * @return string|null the informational link URL.
207
     * @see addTypeLinks()
208
     */
209
    protected function getTypeUrl($class, $method)
210
    {
211
        if (strpos($class, 'yii\\') !== 0) {
212
            return null;
213
        }
214
215
        $page = $this->htmlEncode(strtolower(str_replace('\\', '-', $class)));
216
        $url = "http://www.yiiframework.com/doc-2.0/$page.html";
217
        if ($method) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $method of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
218
            $url .= "#$method()-detail";
219
        }
220
221
        return $url;
222
    }
223
224
    /**
225
     * Renders a view file as a PHP script.
226
     * @param string $_file_ the view file.
227
     * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
228
     * @return string the rendering result
229
     */
230
    public function renderFile($_file_, $_params_)
231
    {
232
        $_params_['handler'] = $this;
233
        if ($this->exception instanceof ErrorException || !Yii::$app->has('view')) {
234
            ob_start();
235
            ob_implicit_flush(false);
236
            extract($_params_, EXTR_OVERWRITE);
237
            require(Yii::getAlias($_file_));
238
239
            return ob_get_clean();
240
        } else {
241
            return Yii::$app->getView()->renderFile($_file_, $_params_, $this);
242
        }
243
    }
244
245
    /**
246
     * Renders the previous exception stack for a given Exception.
247
     * @param \Exception $exception the exception whose precursors should be rendered.
248
     * @return string HTML content of the rendered previous exceptions.
249
     * Empty string if there are none.
250
     */
251
    public function renderPreviousExceptions($exception)
252
    {
253
        if (($previous = $exception->getPrevious()) !== null) {
254
            return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
255
        } else {
256
            return '';
257
        }
258
    }
259
260
    /**
261
     * Renders a single call stack element.
262
     * @param string|null $file name where call has happened.
263
     * @param integer|null $line number on which call has happened.
264
     * @param string|null $class called class name.
265
     * @param string|null $method called function/method name.
266
     * @param array $args array of method arguments.
267
     * @param integer $index number of the call stack element.
268
     * @return string HTML content of the rendered call stack element.
269
     */
270
    public function renderCallStackItem($file, $line, $class, $method, $args, $index)
271
    {
272
        $lines = [];
273
        $begin = $end = 0;
274
        if ($file !== null && $line !== null) {
275
            $line--; // adjust line number from one-based to zero-based
276
            $lines = @file($file);
277
            if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line) {
278
                return '';
279
            }
280
281
            $half = (int) (($index === 1 ? $this->maxSourceLines : $this->maxTraceSourceLines) / 2);
282
            $begin = $line - $half > 0 ? $line - $half : 0;
283
            $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
284
        }
285
286
        return $this->renderFile($this->callStackItemView, [
287
            'file' => $file,
288
            'line' => $line,
289
            'class' => $class,
290
            'method' => $method,
291
            'index' => $index,
292
            'lines' => $lines,
293
            'begin' => $begin,
294
            'end' => $end,
295
            'args' => $args,
296
        ]);
297
    }
298
299
    /**
300
     * Renders the global variables of the request.
301
     * List of global variables is defined in [[displayVars]].
302
     * @return string the rendering result
303
     * @see displayVars
304
     */
305
    public function renderRequest()
306
    {
307
        $request = '';
308
        foreach ($this->displayVars as $name) {
309
            if (!empty($GLOBALS[$name])) {
310
                $request .= '$' . $name . ' = ' . VarDumper::export($GLOBALS[$name]) . ";\n\n";
311
            }
312
        }
313
314
        return '<pre>' . rtrim($request, "\n") . '</pre>';
315
    }
316
317
    /**
318
     * Determines whether given name of the file belongs to the framework.
319
     * @param string $file name to be checked.
320
     * @return boolean whether given name of the file belongs to the framework.
321
     */
322
    public function isCoreFile($file)
323
    {
324
        return $file === null || strpos(realpath($file), YII2_PATH . DIRECTORY_SEPARATOR) === 0;
325
    }
326
327
    /**
328
     * Creates HTML containing link to the page with the information on given HTTP status code.
329
     * @param integer $statusCode to be used to generate information link.
330
     * @param string $statusDescription Description to display after the the status code.
331
     * @return string generated HTML with HTTP status code information.
332
     */
333
    public function createHttpStatusLink($statusCode, $statusDescription)
334
    {
335
        return '<a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#' . (int) $statusCode . '" target="_blank">HTTP ' . (int) $statusCode . ' &ndash; ' . $statusDescription . '</a>';
336
    }
337
338
    /**
339
     * Creates string containing HTML link which refers to the home page of determined web-server software
340
     * and its full name.
341
     * @return string server software information hyperlink.
342
     */
343
    public function createServerInformationLink()
344
    {
345
        $serverUrls = [
346
            'http://httpd.apache.org/' => ['apache'],
347
            'http://nginx.org/' => ['nginx'],
348
            'http://lighttpd.net/' => ['lighttpd'],
349
            'http://gwan.com/' => ['g-wan', 'gwan'],
350
            'http://iis.net/' => ['iis', 'services'],
351
            'http://php.net/manual/en/features.commandline.webserver.php' => ['development'],
352
        ];
353
        if (isset($_SERVER['SERVER_SOFTWARE'])) {
354
            foreach ($serverUrls as $url => $keywords) {
355
                foreach ($keywords as $keyword) {
356
                    if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
357
                        return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
358
                    }
359
                }
360
            }
361
        }
362
363
        return '';
364
    }
365
366
    /**
367
     * Creates string containing HTML link which refers to the page with the current version
368
     * of the framework and version number text.
369
     * @return string framework version information hyperlink.
370
     */
371
    public function createFrameworkVersionLink()
372
    {
373
        return '<a href="http://github.com/yiisoft/yii2/" target="_blank">' . $this->htmlEncode(Yii::getVersion()) . '</a>';
374
    }
375
376
    /**
377
     * Converts arguments array to its string representation
378
     *
379
     * @param array $args arguments array to be converted
380
     * @return string string representation of the arguments array
381
     */
382
    public function argumentsToString($args)
383
    {
384
        $count = 0;
385
        $isAssoc = $args !== array_values($args);
386
387
        foreach ($args as $key => $value) {
388
            $count++;
389
            if ($count>=5) {
390
                if ($count>5) {
391
                    unset($args[$key]);
392
                } else {
393
                    $args[$key] = '...';
394
                }
395
                continue;
396
            }
397
398
            if (is_object($value)) {
399
                $args[$key] = '<span class="title">' . $this->htmlEncode(get_class($value)) . '</span>';
400
            } elseif (is_bool($value)) {
401
                $args[$key] = '<span class="keyword">' . ($value ? 'true' : 'false') . '</span>';
402
            } elseif (is_string($value)) {
403
                $fullValue = $this->htmlEncode($value);
404
                if (mb_strlen($value, 'UTF-8') > 32) {
405
                    $displayValue = $this->htmlEncode(mb_substr($value, 0, 32, 'UTF-8')) . '...';
406
                    $args[$key] = "<span class=\"string\" title=\"$fullValue\">'$displayValue'</span>";
407
                } else {
408
                    $args[$key] = "<span class=\"string\">'$fullValue'</span>";
409
                }
410
            } elseif (is_array($value)) {
411
                $args[$key] = '[' . $this->argumentsToString($value) . ']';
412
            } elseif ($value === null) {
413
                $args[$key] = '<span class="keyword">null</span>';
414
            } elseif (is_resource($value)) {
415
                $args[$key] = '<span class="keyword">resource</span>';
416
            } else {
417
                $args[$key] = '<span class="number">' . $value . '</span>';
418
            }
419
420
            if (is_string($key)) {
421
                $args[$key] = '<span class="string">\'' . $this->htmlEncode($key) . "'</span> => $args[$key]";
422
            } elseif ($isAssoc) {
423
                $args[$key] = "<span class=\"number\">$key</span> => $args[$key]";
424
            }
425
        }
426
        $out = implode(', ', $args);
427
428
        return $out;
429
    }
430
431
    /**
432
     * Returns human-readable exception name
433
     * @param \Exception $exception
434
     * @return string human-readable exception name or null if it cannot be determined
435
     */
436
    public function getExceptionName($exception)
437
    {
438
        if ($exception instanceof \yii\base\Exception || $exception instanceof \yii\base\InvalidCallException || $exception instanceof \yii\base\InvalidParamException || $exception instanceof \yii\base\UnknownMethodException) {
439
            return $exception->getName();
440
        }
441
        return null;
442
    }
443
}
444