-
Notifications
You must be signed in to change notification settings - Fork 4
/
Backtrace.php
292 lines (277 loc) · 9.25 KB
/
Backtrace.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
<?php
/**
* @package Backtrace
* @author Brad Kent <bkfake-github@yahoo.com>
* @license http://opensource.org/licenses/MIT MIT
* @copyright 2020-2024 Brad Kent
* @version v2.2
* @link http://www.github.com/bkdotcom/Backtrace
*/
namespace bdk;
use bdk\Backtrace\Context;
use bdk\Backtrace\Normalizer;
use bdk\Backtrace\SkipInternal;
use bdk\Backtrace\Xdebug;
use Exception;
use InvalidArgumentException;
use ParseError;
use Throwable;
/**
* Utility for getting backtrace
*
* backtrace:
* index 0 is current position
* file/line are calling _from_
* function/class are what's getting called
*/
class Backtrace
{
const INCL_ARGS = 1;
const INCL_OBJECT = 2;
/** @var array */
protected static $callerInfoDefault = array(
'args' => array(),
'class' => null, // where the method is defined
'classCalled' => null, // parent::method()... this will be the parent class
'classContext' => null, // child->method()
'evalLine' => null,
'file' => null,
'function' => null,
'line' => null,
'type' => null,
);
/**
* Add a new namespace or classname to be used to determine when to
* stop iterrating over the backtrace when determining calling info
*
* @param array|string $classes classname(s)
* @param int $level "priority". 0 = will never skip
*
* @return void
* @throws InvalidArgumentException
*/
public static function addInternalClass($classes, $level = 0)
{
SkipInternal::addInternalClass($classes, $level);
}
/**
* Helper method to get backtrace
*
* Uses passed exception, xdebug_get_function_stack, or debug_backtrace
*
* @param int|null $options bitmask of options
* @param int $limit limit the number of stack frames returned.
* @param \Exception|\Throwable $exception (optional) Exception from which to get backtrace
*
* @return array[]
*/
public static function get($options = 0, $limit = 0, $exception = null)
{
$debugBacktraceOpts = self::translateOptions($options);
$limit = $limit ?: null;
$trace = $exception
? self::getExceptionTrace($exception)
: (\array_reverse(Xdebug::getFunctionStack() ?: array())
?: \debug_backtrace($debugBacktraceOpts, $limit > 0 ? $limit + 2 : 0));
$trace = Normalizer::normalize($trace);
$trace = SkipInternal::removeInternalFrames($trace);
// keep the calling file & line, but toss the called function (what initiated trace)
unset($trace[0]['function']);
unset($trace[\count($trace) - 1]['function']); // remove "{main}"
$trace = \array_slice($trace, 0, $limit);
$keysRemove = \array_filter(array(
'args' => ($options & self::INCL_ARGS) !== self::INCL_ARGS,
'object' => ($options & self::INCL_OBJECT) !== self::INCL_OBJECT,
));
return \array_map(static function ($frame) use ($keysRemove) {
$frame = \array_diff_key($frame, $keysRemove);
return $frame;
}, $trace);
}
/**
* Returns information regarding previous call stack position
* call_user_func() and call_user_func_array() are skipped
*
* Information returned:
* function : function/method name
* class : fully qualified classname
* file : file
* line : line number
* type : "->": instance call, "::": static call, null: not object oriented
*
* If a method is defined as static:
* the class value will always be the class in which the method was defined,
* type will always be "::", even if called with an ->
*
* @param int $offset Adjust how far to go back
* @param int $options bitmask options
*
* @return array
*/
public static function getCallerInfo($offset = 0, $options = 0)
{
/*
we need to collect object... we'll remove object at end if undesired
*/
$phpOptions = static::translateOptions($options | self::INCL_OBJECT);
$backtrace = \debug_backtrace($phpOptions, 28);
$backtrace = Normalizer::normalize($backtrace);
$index = SkipInternal::getFirstIndex($backtrace, $offset);
$index = \max($index, 1); // insure we're >= 1
$return = static::callerInfoBuild(\array_slice($backtrace, $index, 2));
if (!($options & self::INCL_OBJECT)) {
unset($return['object']);
}
return $return;
}
/**
* Add context (code snippet) to each frame
*
* context is an array of `lineNumber => line`
*
* @param array $backtrace backtrace frames
* @param int $length number of lines to include
*
* @return array[] backtrace
*/
public static function addContext(array $backtrace, $length = 19)
{
return Context::add($backtrace, $length);
}
/**
* Get lines from a file
*
* Returns array of lineNumber => line
*
* @param string $file filepath
* @param int $start line to start on (1 = first line)
* @param int $length number of lines to return
*
* @return array|false false if file doesn't exist
*/
public static function getFileLines($file, $start = null, $length = null)
{
return Context::getFileLines($file, $start, $length);
}
/**
* Build callerInfo array from given backtrace segment
*
* @param array $backtrace backtrace
*
* @return array[]
*/
private static function callerInfoBuild(array $backtrace)
{
$return = static::$callerInfoDefault;
$iFileLine = 0;
$iFunc = 1;
if (isset($backtrace[$iFunc])) {
$return = \array_merge(
$return,
$backtrace[$iFunc],
self::parseFunction($backtrace[$iFunc]['function'])
);
$return['classCalled'] = $return['class'];
}
if (isset($backtrace[$iFileLine])) {
$fileLineVals = \array_intersect_key($backtrace[$iFileLine], \array_flip(array(
'evalLine',
'file',
'line',
)));
$return = \array_merge($return, $fileLineVals);
}
if ($return['type'] === '->') {
$return['classContext'] = \get_class($backtrace[$iFunc]['object']);
$return = self::callerInfoClassCalled($return);
}
return $return;
}
/**
* Instance method was called... classCalled
*
* @param array $info Caller info
*
* @return array
*/
private static function callerInfoClassCalled(array $info)
{
// parent::method()
// class : classname of parent (or where method defined)
// object : scope / context
$info['classCalled'] = $info['classContext'];
$classDeclared = null;
if ($info['classContext'] !== $info['class']) {
$reflector = new \ReflectionMethod($info['classContext'], $info['function']);
$classDeclared = $reflector->getDeclaringClass()->getName();
}
if ($classDeclared === $info['classContext']) {
// method is (re)declared in classContext, yet that's not what's being executed
// we must have called parent::method()
$info['classCalled'] = $info['class'];
}
return $info;
}
/**
* Get trace from exception
*
* @param Exception|Throwable $exception Exception instance
*
* @return array
*/
private static function getExceptionTrace($exception)
{
if ($exception instanceof ParseError) {
return array();
}
$trace = $exception->getTrace();
$fileLine = array(
'file' => $exception->getFile(),
'line' => $exception->getLine(),
);
if (\array_intersect_assoc($fileLine, \reset($trace) ?: array()) !== $fileLine) {
\array_unshift($trace, $fileLine);
}
return $trace;
}
/**
* Parsed "normalized" function into class, type, & function components
*
* @param string $function Function string to parse
*
* @return array
*/
private static function parseFunction($function)
{
return \preg_match('/^(?<class>\S+)(?<type>::|->)(?<method>\S+)$/', $function, $matches)
? array(
'class' => $matches['class'],
'function' => $matches['method'],
'type' => $matches['type'],
)
: array(
'class' => null,
'function' => $function,
'type' => null,
);
}
/**
* Convert our additive options to PHP's options
*
* @param int|null $options bitmask options
*
* @return int
*/
private static function translateOptions($options)
{
$options = $options ?: 0;
$phpOptions = DEBUG_BACKTRACE_IGNORE_ARGS;
if ($options & self::INCL_ARGS) {
$phpOptions &= ~DEBUG_BACKTRACE_IGNORE_ARGS;
}
if ($options & self::INCL_OBJECT) {
$phpOptions |= DEBUG_BACKTRACE_PROVIDE_OBJECT;
}
return $phpOptions;
}
}