Created
October 9, 2018 12:56
-
-
Save vanderlee/2d759df54b0c33e75204957eb1197555 to your computer and use it in GitHub Desktop.
backtrace(); Safely return current backtrace as array of formatted strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns an array of formatted backtrace lines. | |
* Optional format string may include the following keywords: | |
* index Zero-based order number of backtrace step. | |
* file Path and name of file | |
* line Line number | |
* class Fully qualified name of class | |
* type `::` if class method or `->` if object method | |
* function Name of the method or function | |
* | |
* The call to the backtrace function is always skipped. | |
* Additional calls may be skipped using the `$skip` parameter. | |
* | |
* @param string|null $format Default `'#index file(line): classtypefunction(?)'` | |
* @param int $skip | |
* | |
* @return string[] | |
*/ | |
function backtrace(string $format = null, int $skip = 0) : array | |
{ | |
$format = $format ?: '#index file(line): classtypefunction(?)'; | |
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); | |
array_splice($trace, 0, $skip + 1); | |
return array_map(function ($step, $index) use ($format) { | |
$step['index'] = $index; | |
return strtr($format, $step); | |
}, $trace, range(0, count($trace))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note; formatting of function calls untested. Should look fine, as it's just replaced with empty strings.
Default format based on Exception::getTraceAsString() minus the arguments.