Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaEzzelden/bddc6c8ed359697bbcab3452ccff65f6 to your computer and use it in GitHub Desktop.
Save MostafaEzzelden/bddc6c8ed359697bbcab3452ccff65f6 to your computer and use it in GitHub Desktop.
Make any PHP Exception serializable by flattening complex values in backtrace.
<?php
function flattenExceptionBacktrace(\Exception $exception) {
$traceProperty = (new \ReflectionClass('Exception'))->getProperty('trace');
$traceProperty->setAccessible(true);
$flatten = function(&$value, $key) {
if ($value instanceof \Closure) {
$closureReflection = new \ReflectionFunction($value);
$value = sprintf(
'(Closure at %s:%s)',
$closureReflection->getFileName(),
$closureReflection->getStartLine()
);
} elseif (is_object($value)) {
$value = sprintf('object(%s)', get_class($value));
} elseif (is_resource($value)) {
$value = sprintf('resource(%s)', get_resource_type($value));
}
};
do {
$trace = $traceProperty->getValue($exception);
foreach($trace as &$call) {
array_walk_recursive($call['args'], $flatten);
}
$traceProperty->setValue($exception, $trace);
} while($exception = $exception->getPrevious());
$traceProperty->setAccessible(false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment