Passed
Pull Request — master (#217)
by
unknown
07:47
created

HtmlRenderer::renderTemplate()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 20
c 1
b 0
f 0
nc 16
nop 3
dl 0
loc 30
rs 8.9777
ccs 0
cts 14
cp 0
crap 42
1
<?php
2
3
namespace Yiisoft\Yii\Web\ErrorHandler;
4
5
use Alexkart\CurlBuilder\Command;
6
use Yiisoft\Yii\Web\Info;
7
8
final class HtmlRenderer extends ThrowableRenderer
9
{
10
    private $maxSourceLines = 19;
11
    private $maxTraceLines = 13;
12
13
    private $traceLine = '{html}';
14
15
    public function withMaxSourceLines(int $maxSourceLines): self
16
    {
17
        $new = clone $this;
18
        $new->maxSourceLines = $maxSourceLines;
19
        return $new;
20
    }
21
22
    public function withMaxTraceLines(int $maxTraceLines): self
23
    {
24
        $new = clone $this;
25
        $new->maxTraceLines = $maxTraceLines;
26
        return $new;
27
    }
28
29
    public function withTraceLine(string $traceLine): self
30
    {
31
        $new = clone $this;
32
        $new->traceLine = $traceLine;
33
        return $new;
34
    }
35
36
    public function render(\Throwable $t, string $template = 'error', string $customPath = null): string
37
    {
38
        return $this->renderTemplate($template, [
39
            'throwable' => $t,
40
        ],
41
            $customPath
42
        );
43
    }
44
45
    public function renderVerbose(\Throwable $t, string $template = 'exception', string $customPath = null): string
46
    {
47
        return $this->renderTemplate($template, [
48
            'throwable' => $t,
49
        ],
50
            $customPath
51
        );
52
    }
53
54
    private function htmlEncode(string $text): string
55
    {
56
        return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
57
    }
58
59
    private function renderTemplate(string $template, array $params, string $customPath = null): string
60
    {
61
        if ($customPath) {
62
            $path = $customPath . $template . '.php';
63
        } else {
64
            $path = $this->getDefaultTemplatePath($template);
65
        }
66
67
        if (!file_exists($path)) {
68
            throw new \RuntimeException("$template not found at $path");
69
        }
70
71
        $renderer = function (): void {
72
            extract(func_get_arg(1), EXTR_OVERWRITE);
73
            require func_get_arg(0);
74
        };
75
76
        $obInitialLevel = ob_get_level();
77
        ob_start();
78
        ob_implicit_flush(0);
79
        try {
80
            $renderer->bindTo($this)($path, $params);
81
            return ob_get_clean();
82
        } catch (\Throwable $e) {
83
            while (ob_get_level() > $obInitialLevel) {
84
                if (!@ob_end_clean()) {
85
                    ob_clean();
86
                }
87
            }
88
            throw $e;
89
        }
90
    }
91
92
    private function getDefaultTemplatePath(string $template): string
93
    {
94
        return __DIR__ . '/templates/' . $template . '.php';
95
    }
96
97
    /**
98
     * Renders the previous exception stack for a given Exception.
99
     * @param \Throwable $t the exception whose precursors should be rendered.
100
     * @return string HTML content of the rendered previous exceptions.
101
     * Empty string if there are none.
102
     * @throws \Throwable
103
     */
104
    private function renderPreviousExceptions(\Throwable $t): string
0 ignored issues
show
Unused Code introduced by
The method renderPreviousExceptions() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
105
    {
106
        if (($previous = $t->getPrevious()) !== null) {
107
            return $this->renderTemplate('previousException', ['throwable' => $previous]);
108
        }
109
        return '';
110
    }
111
112
    /**
113
     * Renders a single call stack element.
114
     * @param string|null $file name where call has happened.
115
     * @param int|null $line number on which call has happened.
116
     * @param string|null $class called class name.
117
     * @param string|null $method called function/method name.
118
     * @param array $args array of method arguments.
119
     * @param int $index number of the call stack element.
120
     * @return string HTML content of the rendered call stack element.
121
     * @throws \Throwable
122
     */
123
    private function renderCallStackItem(?string $file, ?int $line, ?string $class, ?string $method, array $args, int $index): string
124
    {
125
        $lines = [];
126
        $begin = $end = 0;
127
        if ($file !== null && $line !== null) {
128
            $line--; // adjust line number from one-based to zero-based
129
            $lines = @file($file);
130
            if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line) {
131
                return '';
132
            }
133
            $half = (int)(($index === 1 ? $this->maxSourceLines : $this->maxTraceLines) / 2);
134
            $begin = $line - $half > 0 ? $line - $half : 0;
135
            $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
136
        }
137
        return $this->renderTemplate('callStackItem', [
138
            'file' => $file,
139
            'line' => $line,
140
            'class' => $class,
141
            'method' => $method,
142
            'index' => $index,
143
            'lines' => $lines,
144
            'begin' => $begin,
145
            'end' => $end,
146
            'args' => $args,
147
        ]);
148
    }
149
150
    /**
151
     * Renders call stack.
152
     * @param \Throwable $t exception to get call stack from
153
     * @return string HTML content of the rendered call stack.
154
     * @throws \Throwable
155
     */
156
    private function renderCallStack(\Throwable $t): string
0 ignored issues
show
Unused Code introduced by
The method renderCallStack() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
157
    {
158
        $out = '<ul>';
159
        $out .= $this->renderCallStackItem($t->getFile(), $t->getLine(), null, null, [], 1);
160
        for ($i = 0, $trace = $t->getTrace(), $length = count($trace); $i < $length; ++$i) {
161
            $file = !empty($trace[$i]['file']) ? $trace[$i]['file'] : null;
162
            $line = !empty($trace[$i]['line']) ? $trace[$i]['line'] : null;
163
            $class = !empty($trace[$i]['class']) ? $trace[$i]['class'] : null;
164
            $function = null;
165
            if (!empty($trace[$i]['function']) && $trace[$i]['function'] !== 'unknown') {
166
                $function = $trace[$i]['function'];
167
            }
168
            $args = !empty($trace[$i]['args']) ? $trace[$i]['args'] : [];
169
            $out .= $this->renderCallStackItem($file, $line, $class, $function, $args, $i + 2);
170
        }
171
        $out .= '</ul>';
172
        return $out;
173
    }
174
175
    /**
176
     * Determines whether given name of the file belongs to the framework.
177
     * @param string $file name to be checked.
178
     * @return bool whether given name of the file belongs to the framework.
179
     */
180
    private function isCoreFile(?string $file): bool
0 ignored issues
show
Unused Code introduced by
The method isCoreFile() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
181
    {
182
        return $file === null || strpos(realpath($file), Info::frameworkPath() . DIRECTORY_SEPARATOR) === 0;
183
    }
184
185
    /**
186
     * Adds informational links to the given PHP type/class.
187
     * @param string $code type/class name to be linkified.
188
     * @param string $title custom title to use
189
     * @return string linkified with HTML type/class name.
190
     * @throws \ReflectionException
191
     */
192
    private function addTypeLinks(string $code, string $title = null): string
0 ignored issues
show
Unused Code introduced by
The method addTypeLinks() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
193
    {
194
        if (preg_match('/(.*?)::([^(]+)/', $code, $matches)) {
195
            [, $class, $method] = $matches;
196
            $text = $title ? $this->htmlEncode($title) : $this->htmlEncode($class) . '::' . $this->htmlEncode($method);
197
        } else {
198
            $class = $code;
199
            $method = null;
200
            $text = $title ? $this->htmlEncode($title) : $this->htmlEncode($class);
201
        }
202
        $url = null;
203
        $shouldGenerateLink = true;
204
        if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) {
205
            $reflection = new \ReflectionClass($class);
206
            if ($reflection->hasMethod($method)) {
207
                $reflectionMethod = $reflection->getMethod($method);
208
                $shouldGenerateLink = $reflectionMethod->isPublic() || $reflectionMethod->isProtected();
209
            } else {
210
                $shouldGenerateLink = false;
211
            }
212
        }
213
        if ($shouldGenerateLink) {
214
            $url = $this->getTypeUrl($class, $method);
215
        }
216
        if ($url === null) {
217
            return $text;
218
        }
219
        return '<a href="' . $url . '" target="_blank">' . $text . '</a>';
220
    }
221
222
    /**
223
     * Returns the informational link URL for a given PHP type/class.
224
     * @param string $class the type or class name.
225
     * @param string|null $method the method name.
226
     * @return string|null the informational link URL.
227
     * @see addTypeLinks()
228
     */
229
    private function getTypeUrl(?string $class, ?string $method): ?string
230
    {
231
        if (strncmp($class, 'Yiisoft\\', 8) !== 0) {
232
            return null;
233
        }
234
        $page = $this->htmlEncode(strtolower(str_replace('\\', '-', $class)));
235
        $url = "http://www.yiiframework.com/doc-3.0/$page.html";
236
        if ($method) {
237
            $url .= "#$method()-detail";
238
        }
239
        return $url;
240
    }
241
242
    /**
243
     * Converts arguments array to its string representation.
244
     *
245
     * @param array $args arguments array to be converted
246
     * @return string string representation of the arguments array
247
     */
248
    private function argumentsToString(array $args): string
249
    {
250
        $count = 0;
251
        $isAssoc = $args !== array_values($args);
252
        foreach ($args as $key => $value) {
253
            $count++;
254
            if ($count >= 5) {
255
                if ($count > 5) {
256
                    unset($args[$key]);
257
                } else {
258
                    $args[$key] = '...';
259
                }
260
                continue;
261
            }
262
            if (is_object($value)) {
263
                $args[$key] = '<span class="title">' . $this->htmlEncode(get_class($value)) . '</span>';
264
            } elseif (is_bool($value)) {
265
                $args[$key] = '<span class="keyword">' . ($value ? 'true' : 'false') . '</span>';
266
            } elseif (is_string($value)) {
267
                $fullValue = $this->htmlEncode($value);
268
                if (mb_strlen($value, 'UTF-8') > 32) {
269
                    $displayValue = $this->htmlEncode(mb_substr($value, 0, 32, 'UTF-8')) . '...';
270
                    $args[$key] = "<span class=\"string\" title=\"$fullValue\">'$displayValue'</span>";
271
                } else {
272
                    $args[$key] = "<span class=\"string\">'$fullValue'</span>";
273
                }
274
            } elseif (is_array($value)) {
275
                $args[$key] = '[' . $this->argumentsToString($value) . ']';
276
            } elseif ($value === null) {
277
                $args[$key] = '<span class="keyword">null</span>';
278
            } elseif (is_resource($value)) {
279
                $args[$key] = '<span class="keyword">resource</span>';
280
            } else {
281
                $args[$key] = '<span class="number">' . $value . '</span>';
282
            }
283
            if (is_string($key)) {
284
                $args[$key] = '<span class="string">\'' . $this->htmlEncode($key) . "'</span> => $args[$key]";
285
            } elseif ($isAssoc) {
286
                $args[$key] = "<span class=\"number\">$key</span> => $args[$key]";
287
            }
288
        }
289
        return implode(', ', $args);
290
    }
291
292
    /**
293
     * Renders the information about request.
294
     * @return string the rendering result
295
     */
296
    private function renderRequest(): string
0 ignored issues
show
Unused Code introduced by
The method renderRequest() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
297
    {
298
        if ($this->request === null) {
299
            return '';
300
        }
301
302
        $request = $this->request;
303
304
        $output = '';
305
306
        $output .= $request->getMethod() . ' ' . $request->getUri() . "\n";
307
308
        foreach ($request->getHeaders() as $name => $values) {
309
            if ($name === 'Host') {
310
                continue;
311
            }
312
313
            foreach ($values as $value) {
314
                $output .= "$name: $value\n";
315
            }
316
        }
317
318
        $output .= "\n" . $request->getBody() . "\n\n";
319
320
        return '<pre>' . $this->htmlEncode(rtrim($output, "\n")) . '</pre>';
321
    }
322
323
    private function renderCurl(): string
0 ignored issues
show
Unused Code introduced by
The method renderCurl() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
324
    {
325
        try {
326
            $output = (new Command())->setRequest($this->request)->build();
327
        } catch (\Throwable $e) {
328
            $output = 'Error generating curl command: ' . $e->getMessage();
329
        }
330
331
        return $this->htmlEncode($output);
332
    }
333
334
335
    /**
336
     * Creates string containing HTML link which refers to the home page of determined web-server software
337
     * and its full name.
338
     * @return string server software information hyperlink.
339
     */
340
    private function createServerInformationLink(): string
0 ignored issues
show
Unused Code introduced by
The method createServerInformationLink() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
341
    {
342
        if (isset($_SERVER['SERVER_SOFTWARE'])) {
343
            $serverUrls = [
344
                'http://httpd.apache.org/' => ['apache'],
345
                'http://nginx.org/' => ['nginx'],
346
                'http://lighttpd.net/' => ['lighttpd'],
347
                'http://gwan.com/' => ['g-wan', 'gwan'],
348
                'http://iis.net/' => ['iis', 'services'],
349
                'https://secure.php.net/manual/en/features.commandline.webserver.php' => ['development'],
350
            ];
351
352
            foreach ($serverUrls as $url => $keywords) {
353
                foreach ($keywords as $keyword) {
354
                    if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
355
                        return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
356
                    }
357
                }
358
            }
359
        }
360
        return '';
361
    }
362
363
    /**
364
     * Creates string containing HTML link which refers to the page with the current version
365
     * of the framework and version number text.
366
     * @return string framework version information hyperlink.
367
     */
368
    public function createFrameworkVersionLink(): string
369
    {
370
        return '<a href="http://github.com/yiisoft/yii-web/" target="_blank">' . $this->htmlEncode(Info::frameworkVersion()) . '</a>';
371
    }
372
}
373