ExceptionFormatter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /** @package verysimple::Util */
  3. /**
  4. * Formatter for formatting Exceptions and stack traces
  5. *
  6. * @package verysimple::String
  7. * @author Jason Hinkle
  8. * @copyright 1997-2008 VerySimple, Inc.
  9. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  10. * @version 1.0
  11. */
  12. class ExceptionFormatter
  13. {
  14. /**
  15. * This is a utility function for tracing errors. It will return a string that
  16. * displys the current execution stack
  17. *
  18. * @param string $msg a debugging message to include
  19. * @param int $depth how far to go back in the stack (default = unlimited)
  20. * @param string $join the delimiter between lines
  21. * @param bool $show_lines true to include line numbers
  22. */
  23. static function GetTraceAsString($msg = "DEBUG", $depth = 0, $join = " :: ", $show_lines = true)
  24. {
  25. $error = new Exception($msg);
  26. return self::FormatTrace($error->getTrace(), $depth, $join, $show_lines);
  27. }
  28. /**
  29. * Formats the debug_backtrace array into a printable string.
  30. * You can create a debug traceback using $exception->getTrace()
  31. * or using the php debug_backtrace() function
  32. *
  33. * @access public
  34. * @param array debug_backtrace. For example: debug_backtrace() -or- $exception->getTrace()
  35. * @param int $depth how far to go back in the stack (default = unlimited)
  36. * @param string $join the delimiter between lines
  37. * @param bool $show_lines true to include line numbers
  38. */
  39. static function FormatTrace($tb, $depth = 0, $join = " :: ", $show_lines = true)
  40. {
  41. $msg = "";
  42. $delim = "";
  43. $calling_function = "";
  44. $calling_line = "[?]";
  45. $levels = count($tb);
  46. if ($depth == 0) $depth = $levels;
  47. for ($x = $levels; $x > 0; $x--)
  48. {
  49. $stack = $tb[$x-1];
  50. $s_file = isset($stack['file']) ? basename($stack['file']) : "[?]";
  51. $s_line = isset($stack['line']) ? $stack['line'] : "[?]";
  52. $s_function = isset($stack['function']) ? $stack['function'] : "";
  53. $s_class = isset($stack['class']) ? $stack['class'] : "";
  54. $s_type = isset($stack['type']) ? $stack['type'] : "";
  55. if ($depth >= $x)
  56. {
  57. $msg .= $delim . "$calling_function" . ($show_lines ? " ($s_file Line $s_line)" : "");
  58. $delim = $join;
  59. }
  60. $calling_function = $s_class . $s_type . $s_function;
  61. }
  62. return $msg;
  63. }
  64. }
  65. ?>