<?php
Imports("System.Diagnostics.StackFrame");
Imports("System.Text.StringBuilder");
Imports("Microsoft.VisualBasic.Strings");
class StackTrace {
var $frames;
public function FrameCount() {
if (empty($this->frames)) {
return 0;
} else {
return count($this->frames);
}
}
public function __construct($backtrace = null) {
$first = true;
$frames = [];
if (!$backtrace) {
$backtrace = debug_backtrace();
} else {
$first = false;
}
foreach($backtrace as $k => $v) {
if ($first) {
# 第一个栈片段信息是当前的这个函数
# 跳过
$first = false;
continue;
} else {
array_push($frames, new StackFrame($v));
}
}
$this->frames = $frames;
}
public function GetFrame($index) {
return $this->frames[$index];
}
public static function GetCallStack() {
return new StackTrace(debug_backtrace());
}
public static function GetCallerFile() {
$caller = False;
foreach(debug_backtrace() as $k => $v) {
if ($caller) {
return $v["file"];
} else {
$caller = True;
}
}
}
public static function GetCallerMethodName() {
$trace = debug_backtrace();
$caller = $trace[2];
return $caller['function'];
}
public function ToString($html = true) {
$newLine = $html ? "<br />" . PHP_EOL : PHP_EOL;
$trace = new StringBuilder("", $newLine);
if ($html) {
$trace->Append("<code>");
}
foreach($this->frames as $frame) {
$trace->AppendLine($frame->ToString());
}
if ($html) {
$trace->Append("</code>");
}
return $trace->ToString();
}
}
?>