ExceptionHandler.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Debug\Exception\FlattenException;
  13. if (!defined('ENT_SUBSTITUTE')) {
  14. define('ENT_SUBSTITUTE', 8);
  15. }
  16. /**
  17. * ExceptionHandler converts an exception to a Response object.
  18. *
  19. * It is mostly useful in debug mode to replace the default PHP/XDebug
  20. * output with something prettier and more useful.
  21. *
  22. * As this class is mainly used during Kernel boot, where nothing is yet
  23. * available, the Response content is always HTML.
  24. *
  25. * @author Fabien Potencier <fabien@symfony.com>
  26. */
  27. class ExceptionHandler
  28. {
  29. private $debug;
  30. private $charset;
  31. public function __construct($debug = true, $charset = 'UTF-8')
  32. {
  33. $this->debug = $debug;
  34. $this->charset = $charset;
  35. }
  36. /**
  37. * Registers the exception handler.
  38. *
  39. * @param Boolean $debug
  40. *
  41. * @return ExceptionHandler The registered exception handler
  42. */
  43. public static function register($debug = true)
  44. {
  45. $handler = new static($debug);
  46. set_exception_handler(array($handler, 'handle'));
  47. return $handler;
  48. }
  49. /**
  50. * Sends a response for the given Exception.
  51. *
  52. * If you have the Symfony HttpFoundation component installed,
  53. * this method will use it to create and send the response. If not,
  54. * it will fallback to plain PHP functions.
  55. *
  56. * @param \Exception $exception An \Exception instance
  57. *
  58. * @see sendPhpResponse
  59. * @see createResponse
  60. */
  61. public function handle(\Exception $exception)
  62. {
  63. if (class_exists('Symfony\Component\HttpFoundation\Response')) {
  64. $this->createResponse($exception)->send();
  65. } else {
  66. $this->sendPhpResponse($exception);
  67. }
  68. }
  69. /**
  70. * Sends the error associated with the given Exception as a plain PHP response.
  71. *
  72. * This method uses plain PHP functions like header() and echo to output
  73. * the response.
  74. *
  75. * @param \Exception|FlattenException $exception An \Exception instance
  76. */
  77. public function sendPhpResponse($exception)
  78. {
  79. if (!$exception instanceof FlattenException) {
  80. $exception = FlattenException::create($exception);
  81. }
  82. header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
  83. foreach ($exception->getHeaders() as $name => $value) {
  84. header($name.': '.$value, false);
  85. }
  86. echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
  87. }
  88. /**
  89. * Creates the error Response associated with the given Exception.
  90. *
  91. * @param \Exception|FlattenException $exception An \Exception instance
  92. *
  93. * @return Response A Response instance
  94. */
  95. public function createResponse($exception)
  96. {
  97. if (!$exception instanceof FlattenException) {
  98. $exception = FlattenException::create($exception);
  99. }
  100. return new Response($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders());
  101. }
  102. /**
  103. * Gets the HTML content associated with the given exception.
  104. *
  105. * @param FlattenException $exception A FlattenException instance
  106. *
  107. * @return string The content as a string
  108. */
  109. public function getContent(FlattenException $exception)
  110. {
  111. switch ($exception->getStatusCode()) {
  112. case 404:
  113. $title = 'Sorry, the page you are looking for could not be found.';
  114. break;
  115. default:
  116. $title = 'Whoops, looks like something went wrong.';
  117. }
  118. $content = '';
  119. if ($this->debug) {
  120. try {
  121. $count = count($exception->getAllPrevious());
  122. $total = $count + 1;
  123. foreach ($exception->toArray() as $position => $e) {
  124. $ind = $count - $position + 1;
  125. $class = $this->abbrClass($e['class']);
  126. $message = nl2br($e['message']);
  127. $content .= sprintf(<<<EOF
  128. <div class="block_exception clear_fix">
  129. <h2><span>%d/%d</span> %s: %s</h2>
  130. </div>
  131. <div class="block">
  132. <ol class="traces list_exception">
  133. EOF
  134. , $ind, $total, $class, $message);
  135. foreach ($e['trace'] as $trace) {
  136. $content .= ' <li>';
  137. if ($trace['function']) {
  138. $content .= sprintf('at %s%s%s(%s)', $this->abbrClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
  139. }
  140. if (isset($trace['file']) && isset($trace['line'])) {
  141. if ($linkFormat = ini_get('xdebug.file_link_format')) {
  142. $link = str_replace(array('%f', '%l'), array($trace['file'], $trace['line']), $linkFormat);
  143. $content .= sprintf(' in <a href="%s" title="Go to source">%s line %s</a>', $link, $trace['file'], $trace['line']);
  144. } else {
  145. $content .= sprintf(' in %s line %s', $trace['file'], $trace['line']);
  146. }
  147. }
  148. $content .= "</li>\n";
  149. }
  150. $content .= " </ol>\n</div>\n";
  151. }
  152. } catch (\Exception $e) {
  153. // something nasty happened and we cannot throw an exception anymore
  154. if ($this->debug) {
  155. $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($exception), $exception->getMessage());
  156. } else {
  157. $title = 'Whoops, looks like something went wrong.';
  158. }
  159. }
  160. }
  161. return <<<EOF
  162. <div id="sf-resetcontent" class="sf-reset">
  163. <h1>$title</h1>
  164. $content
  165. </div>
  166. EOF;
  167. }
  168. /**
  169. * Gets the stylesheet associated with the given exception.
  170. *
  171. * @param FlattenException $exception A FlattenException instance
  172. *
  173. * @return string The stylesheet as a string
  174. */
  175. public function getStylesheet(FlattenException $exception)
  176. {
  177. return <<<EOF
  178. .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
  179. .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
  180. .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
  181. .sf-reset .clear_fix { display:inline-block; }
  182. .sf-reset * html .clear_fix { height:1%; }
  183. .sf-reset .clear_fix { display:block; }
  184. .sf-reset, .sf-reset .block { margin: auto }
  185. .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
  186. .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
  187. .sf-reset strong { font-weight:bold; }
  188. .sf-reset a { color:#6c6159; }
  189. .sf-reset a img { border:none; }
  190. .sf-reset a:hover { text-decoration:underline; }
  191. .sf-reset em { font-style:italic; }
  192. .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
  193. .sf-reset h2 span { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; }
  194. .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
  195. .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
  196. -webkit-border-bottom-right-radius: 16px;
  197. -webkit-border-bottom-left-radius: 16px;
  198. -moz-border-radius-bottomright: 16px;
  199. -moz-border-radius-bottomleft: 16px;
  200. border-bottom-right-radius: 16px;
  201. border-bottom-left-radius: 16px;
  202. border-bottom:1px solid #ccc;
  203. border-right:1px solid #ccc;
  204. border-left:1px solid #ccc;
  205. }
  206. .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
  207. -webkit-border-top-left-radius: 16px;
  208. -webkit-border-top-right-radius: 16px;
  209. -moz-border-radius-topleft: 16px;
  210. -moz-border-radius-topright: 16px;
  211. border-top-left-radius: 16px;
  212. border-top-right-radius: 16px;
  213. border-top:1px solid #ccc;
  214. border-right:1px solid #ccc;
  215. border-left:1px solid #ccc;
  216. overflow: hidden;
  217. word-wrap: break-word;
  218. }
  219. .sf-reset li a { background:none; color:#868686; text-decoration:none; }
  220. .sf-reset li a:hover { background:none; color:#313131; text-decoration:underline; }
  221. .sf-reset ol { padding: 10px 0; }
  222. .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
  223. -webkit-border-radius: 10px;
  224. -moz-border-radius: 10px;
  225. border-radius: 10px;
  226. border: 1px solid #ccc;
  227. }
  228. EOF;
  229. }
  230. private function decorate($content, $css)
  231. {
  232. return <<<EOF
  233. <!DOCTYPE html>
  234. <html>
  235. <head>
  236. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  237. <meta name="robots" content="noindex,nofollow" />
  238. <style>
  239. /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
  240. 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;}
  241. html { background: #eee; padding: 10px }
  242. img { border: 0; }
  243. #sf-resetcontent { width:970px; margin:0 auto; }
  244. $css
  245. </style>
  246. </head>
  247. <body>
  248. $content
  249. </body>
  250. </html>
  251. EOF;
  252. }
  253. private function abbrClass($class)
  254. {
  255. $parts = explode('\\', $class);
  256. return sprintf("<abbr title=\"%s\">%s</abbr>", $class, array_pop($parts));
  257. }
  258. /**
  259. * Formats an array as a string.
  260. *
  261. * @param array $args The argument array
  262. *
  263. * @return string
  264. */
  265. private function formatArgs(array $args)
  266. {
  267. $result = array();
  268. foreach ($args as $key => $item) {
  269. if ('object' === $item[0]) {
  270. $formattedValue = sprintf("<em>object</em>(%s)", $this->abbrClass($item[1]));
  271. } elseif ('array' === $item[0]) {
  272. $formattedValue = sprintf("<em>array</em>(%s)", is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
  273. } elseif ('string' === $item[0]) {
  274. $formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset));
  275. } elseif ('null' === $item[0]) {
  276. $formattedValue = '<em>null</em>';
  277. } elseif ('boolean' === $item[0]) {
  278. $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
  279. } elseif ('resource' === $item[0]) {
  280. $formattedValue = '<em>resource</em>';
  281. } else {
  282. $formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset), true));
  283. }
  284. $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
  285. }
  286. return implode(', ', $result);
  287. }
  288. }