-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBacktracer.php
93 lines (82 loc) · 2.59 KB
/
Backtracer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace TiGR\DatabaseLogger;
class Backtracer
{
private $includeDirs = [];
private $excludeDirs = [];
public function __construct()
{
$this->addExcludeDir(__DIR__);
}
public function addExcludeDir($dir)
{
$this->excludeDirs[] = $dir;
}
public function addIncludeDir($namespace)
{
$this->includeDirs[] = $namespace;
}
/**
* Returns array of string representations of backtrace steps.
*
* @param int $maxDepth
* @return array
*/
public function getBacktrace($maxDepth = 10)
{
$result = [];
foreach ($this->getRawBacktrace($maxDepth) as $trace) {
$file = (isset($trace['file']) ? basename(substr($trace['file'], strlen(getcwd()) + 1)) : '');
$function = (isset($trace['function']) ? $trace['function'] : '');
if (isset($trace['class'])) {
$class = explode("\\", basename($trace['class']));
$class = array_pop($class);
$result[] = sprintf('%s:%d %s%s%s()', $file, isset($trace['line']) ? $trace['line'] : '', $class, $trace['type'], $function);
} else {
$result[] = $file . ':' . $trace['line'];
}
}
return $result;
}
/**
* Returns filtered backtrace as is.
*
* @param int $maxDepth
* @return array
*/
public function getRawBacktrace($maxDepth = 10)
{
$backtrace = debug_backtrace(0);
$result = [];
foreach ($backtrace as $trace) {
if (in_array($trace['function'], ['__call', '__callStatic', 'call_user_func', 'call_user_func_array']) or !isset($trace['line'])) {
continue;
}
if (isset($trace['file'])) {
if (!empty($this->excludeDirs)) {
foreach ($this->excludeDirs as $dir) {
if (strpos($trace['file'], $dir) === 0) {
continue 2;
}
}
}
if (!empty($this->includeDirs)) {
$match = false;
foreach ($this->includeDirs as $dir) {
if (strpos($trace['file'], $dir) === 0) {
$match = true;
}
}
if (!$match) {
continue;
}
}
}
$result[] = $trace;
if (--$maxDepth == 0) {
break;
}
}
return $result;
}
}