Skip to content

Instantly share code, notes, and snippets.

@vanderlee
Created October 9, 2018 12:56
Show Gist options
  • Save vanderlee/2d759df54b0c33e75204957eb1197555 to your computer and use it in GitHub Desktop.
Save vanderlee/2d759df54b0c33e75204957eb1197555 to your computer and use it in GitHub Desktop.
backtrace(); Safely return current backtrace as array of formatted strings
<?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)));
}
@vanderlee
Copy link
Author

vanderlee commented Oct 9, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment