Projekt

Obecné

Profil

Stáhnout (15.8 KB) Statistiky
| Větev: | Revize:
1
<?php
2

    
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

    
12
namespace Symfony\Component\Debug;
13

    
14
use Symfony\Component\Debug\Exception\FlattenException;
15
use Symfony\Component\Debug\Exception\OutOfMemoryException;
16

    
17
/**
18
 * ExceptionHandler converts an exception to a Response object.
19
 *
20
 * It is mostly useful in debug mode to replace the default PHP/XDebug
21
 * output with something prettier and more useful.
22
 *
23
 * As this class is mainly used during Kernel boot, where nothing is yet
24
 * available, the Response content is always HTML.
25
 *
26
 * @author Fabien Potencier <fabien@symfony.com>
27
 * @author Nicolas Grekas <p@tchwork.com>
28
 */
29
class ExceptionHandler
30
{
31
    private $debug;
32
    private $charset;
33
    private $handler;
34
    private $caughtBuffer;
35
    private $caughtLength;
36
    private $fileLinkFormat;
37

    
38
    public function __construct($debug = true, $charset = null, $fileLinkFormat = null)
39
    {
40
        $this->debug = $debug;
41
        $this->charset = $charset ?: ini_get('default_charset') ?: 'UTF-8';
42
        $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
43
    }
44

    
45
    /**
46
     * Registers the exception handler.
47
     *
48
     * @param bool        $debug          Enable/disable debug mode, where the stack trace is displayed
49
     * @param string|null $charset        The charset used by exception messages
50
     * @param string|null $fileLinkFormat The IDE link template
51
     *
52
     * @return ExceptionHandler The registered exception handler
53
     */
54
    public static function register($debug = true, $charset = null, $fileLinkFormat = null)
55
    {
56
        $handler = new static($debug, $charset, $fileLinkFormat);
57

    
58
        $prev = set_exception_handler(array($handler, 'handle'));
59
        if (is_array($prev) && $prev[0] instanceof ErrorHandler) {
60
            restore_exception_handler();
61
            $prev[0]->setExceptionHandler(array($handler, 'handle'));
62
        }
63

    
64
        return $handler;
65
    }
66

    
67
    /**
68
     * Sets a user exception handler.
69
     *
70
     * @param callable $handler An handler that will be called on Exception
71
     *
72
     * @return callable|null The previous exception handler if any
73
     */
74
    public function setHandler(callable $handler = null)
75
    {
76
        $old = $this->handler;
77
        $this->handler = $handler;
78

    
79
        return $old;
80
    }
81

    
82
    /**
83
     * Sets the format for links to source files.
84
     *
85
     * @param string $format The format for links to source files
86
     *
87
     * @return string The previous file link format
88
     */
89
    public function setFileLinkFormat($format)
90
    {
91
        $old = $this->fileLinkFormat;
92
        $this->fileLinkFormat = $format;
93

    
94
        return $old;
95
    }
96

    
97
    /**
98
     * Sends a response for the given Exception.
99
     *
100
     * To be as fail-safe as possible, the exception is first handled
101
     * by our simple exception handler, then by the user exception handler.
102
     * The latter takes precedence and any output from the former is cancelled,
103
     * if and only if nothing bad happens in this handling path.
104
     */
105
    public function handle(\Exception $exception)
106
    {
107
        if (null === $this->handler || $exception instanceof OutOfMemoryException) {
108
            $this->sendPhpResponse($exception);
109

    
110
            return;
111
        }
112

    
113
        $caughtLength = $this->caughtLength = 0;
114

    
115
        ob_start(function ($buffer) {
116
            $this->caughtBuffer = $buffer;
117

    
118
            return '';
119
        });
120

    
121
        $this->sendPhpResponse($exception);
122
        while (null === $this->caughtBuffer && ob_end_flush()) {
123
            // Empty loop, everything is in the condition
124
        }
125
        if (isset($this->caughtBuffer[0])) {
126
            ob_start(function ($buffer) {
127
                if ($this->caughtLength) {
128
                    // use substr_replace() instead of substr() for mbstring overloading resistance
129
                    $cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
130
                    if (isset($cleanBuffer[0])) {
131
                        $buffer = $cleanBuffer;
132
                    }
133
                }
134

    
135
                return $buffer;
136
            });
137

    
138
            echo $this->caughtBuffer;
139
            $caughtLength = ob_get_length();
140
        }
141
        $this->caughtBuffer = null;
142

    
143
        try {
144
            call_user_func($this->handler, $exception);
145
            $this->caughtLength = $caughtLength;
146
        } catch (\Exception $e) {
147
            if (!$caughtLength) {
148
                // All handlers failed. Let PHP handle that now.
149
                throw $exception;
150
            }
151
        }
152
    }
153

    
154
    /**
155
     * Sends the error associated with the given Exception as a plain PHP response.
156
     *
157
     * This method uses plain PHP functions like header() and echo to output
158
     * the response.
159
     *
160
     * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
161
     */
162
    public function sendPhpResponse($exception)
163
    {
164
        if (!$exception instanceof FlattenException) {
165
            $exception = FlattenException::create($exception);
166
        }
167

    
168
        if (!headers_sent()) {
169
            header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
170
            foreach ($exception->getHeaders() as $name => $value) {
171
                header($name.': '.$value, false);
172
            }
173
            header('Content-Type: text/html; charset='.$this->charset);
174
        }
175

    
176
        echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
177
    }
178

    
179
    /**
180
     * Gets the full HTML content associated with the given exception.
181
     *
182
     * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
183
     *
184
     * @return string The HTML content as a string
185
     */
186
    public function getHtml($exception)
187
    {
188
        if (!$exception instanceof FlattenException) {
189
            $exception = FlattenException::create($exception);
190
        }
191

    
192
        return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
193
    }
194

    
195
    /**
196
     * Gets the HTML content associated with the given exception.
197
     *
198
     * @param FlattenException $exception A FlattenException instance
199
     *
200
     * @return string The content as a string
201
     */
202
    public function getContent(FlattenException $exception)
203
    {
204
        switch ($exception->getStatusCode()) {
205
            case 404:
206
                $title = 'Sorry, the page you are looking for could not be found.';
207
                break;
208
            default:
209
                $title = 'Whoops, looks like something went wrong.';
210
        }
211

    
212
        $content = '';
213
        if ($this->debug) {
214
            try {
215
                $count = count($exception->getAllPrevious());
216
                $total = $count + 1;
217
                foreach ($exception->toArray() as $position => $e) {
218
                    $ind = $count - $position + 1;
219
                    $class = $this->formatClass($e['class']);
220
                    $message = nl2br($this->escapeHtml($e['message']));
221
                    $content .= sprintf(<<<'EOF'
222
                        <h2 class="block_exception clear_fix">
223
                            <span class="exception_counter">%d/%d</span>
224
                            <span class="exception_title">%s%s:</span>
225
                            <span class="exception_message">%s</span>
226
                        </h2>
227
                        <div class="block">
228
                            <ol class="traces list_exception">
229

    
230
EOF
231
                        , $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message);
232
                    foreach ($e['trace'] as $trace) {
233
                        $content .= '       <li>';
234
                        if ($trace['function']) {
235
                            $content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
236
                        }
237
                        if (isset($trace['file']) && isset($trace['line'])) {
238
                            $content .= $this->formatPath($trace['file'], $trace['line']);
239
                        }
240
                        $content .= "</li>\n";
241
                    }
242

    
243
                    $content .= "    </ol>\n</div>\n";
244
                }
245
            } catch (\Exception $e) {
246
                // something nasty happened and we cannot throw an exception anymore
247
                if ($this->debug) {
248
                    $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $this->escapeHtml($e->getMessage()));
249
                } else {
250
                    $title = 'Whoops, looks like something went wrong.';
251
                }
252
            }
253
        }
254

    
255
        return <<<EOF
256
            <div id="sf-resetcontent" class="sf-reset">
257
                <h1>$title</h1>
258
                $content
259
            </div>
260
EOF;
261
    }
262

    
263
    /**
264
     * Gets the stylesheet associated with the given exception.
265
     *
266
     * @param FlattenException $exception A FlattenException instance
267
     *
268
     * @return string The stylesheet as a string
269
     */
270
    public function getStylesheet(FlattenException $exception)
271
    {
272
        return <<<'EOF'
273
            .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
274
            .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
275
            .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
276
            .sf-reset .clear_fix { display:inline-block; }
277
            .sf-reset * html .clear_fix { height:1%; }
278
            .sf-reset .clear_fix { display:block; }
279
            .sf-reset, .sf-reset .block { margin: auto }
280
            .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
281
            .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
282
            .sf-reset strong { font-weight:bold; }
283
            .sf-reset a { color:#6c6159; cursor: default; }
284
            .sf-reset a img { border:none; }
285
            .sf-reset a:hover { text-decoration:underline; }
286
            .sf-reset em { font-style:italic; }
287
            .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
288
            .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
289
            .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
290
            .sf-reset .exception_message { margin-left: 3em; display: block; }
291
            .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
292
            .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
293
                -webkit-border-bottom-right-radius: 16px;
294
                -webkit-border-bottom-left-radius: 16px;
295
                -moz-border-radius-bottomright: 16px;
296
                -moz-border-radius-bottomleft: 16px;
297
                border-bottom-right-radius: 16px;
298
                border-bottom-left-radius: 16px;
299
                border-bottom:1px solid #ccc;
300
                border-right:1px solid #ccc;
301
                border-left:1px solid #ccc;
302
            }
303
            .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
304
                -webkit-border-top-left-radius: 16px;
305
                -webkit-border-top-right-radius: 16px;
306
                -moz-border-radius-topleft: 16px;
307
                -moz-border-radius-topright: 16px;
308
                border-top-left-radius: 16px;
309
                border-top-right-radius: 16px;
310
                border-top:1px solid #ccc;
311
                border-right:1px solid #ccc;
312
                border-left:1px solid #ccc;
313
                overflow: hidden;
314
                word-wrap: break-word;
315
            }
316
            .sf-reset a { background:none; color:#868686; text-decoration:none; }
317
            .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
318
            .sf-reset ol { padding: 10px 0; }
319
            .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
320
                -webkit-border-radius: 10px;
321
                -moz-border-radius: 10px;
322
                border-radius: 10px;
323
                border: 1px solid #ccc;
324
            }
325
EOF;
326
    }
327

    
328
    private function decorate($content, $css)
329
    {
330
        return <<<EOF
331
<!DOCTYPE html>
332
<html>
333
    <head>
334
        <meta charset="{$this->charset}" />
335
        <meta name="robots" content="noindex,nofollow" />
336
        <style>
337
            /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
338
            html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
339

    
340
            html { background: #eee; padding: 10px }
341
            img { border: 0; }
342
            #sf-resetcontent { width:970px; margin:0 auto; }
343
            $css
344
        </style>
345
    </head>
346
    <body>
347
        $content
348
    </body>
349
</html>
350
EOF;
351
    }
352

    
353
    private function formatClass($class)
354
    {
355
        $parts = explode('\\', $class);
356

    
357
        return sprintf('<abbr title="%s">%s</abbr>', $class, array_pop($parts));
358
    }
359

    
360
    private function formatPath($path, $line)
361
    {
362
        $path = $this->escapeHtml($path);
363
        $file = preg_match('#[^/\\\\]*$#', $path, $file) ? $file[0] : $path;
364

    
365
        if ($linkFormat = $this->fileLinkFormat) {
366
            $link = strtr($this->escapeHtml($linkFormat), array('%f' => $path, '%l' => (int) $line));
367

    
368
            return sprintf(' in <a href="%s" title="Go to source">%s line %d</a>', $link, $file, $line);
369
        }
370

    
371
        return sprintf(' in <a title="%s line %3$d" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">%s line %d</a>', $path, $file, $line);
372
    }
373

    
374
    /**
375
     * Formats an array as a string.
376
     *
377
     * @param array $args The argument array
378
     *
379
     * @return string
380
     */
381
    private function formatArgs(array $args)
382
    {
383
        $result = array();
384
        foreach ($args as $key => $item) {
385
            if ('object' === $item[0]) {
386
                $formattedValue = sprintf('<em>object</em>(%s)', $this->formatClass($item[1]));
387
            } elseif ('array' === $item[0]) {
388
                $formattedValue = sprintf('<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
389
            } elseif ('string' === $item[0]) {
390
                $formattedValue = sprintf("'%s'", $this->escapeHtml($item[1]));
391
            } elseif ('null' === $item[0]) {
392
                $formattedValue = '<em>null</em>';
393
            } elseif ('boolean' === $item[0]) {
394
                $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
395
            } elseif ('resource' === $item[0]) {
396
                $formattedValue = '<em>resource</em>';
397
            } else {
398
                $formattedValue = str_replace("\n", '', var_export($this->escapeHtml((string) $item[1]), true));
399
            }
400

    
401
            $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
402
        }
403

    
404
        return implode(', ', $result);
405
    }
406

    
407
    /**
408
     * HTML-encodes a string.
409
     */
410
    private function escapeHtml($str)
411
    {
412
        return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, $this->charset);
413
    }
414
}
(7-7/11)