Forked from Thinkscape/flattenExceptionBacktrace.php
Last active
July 4, 2021 10:44
-
-
Save nh-mike/fde9f69a57bc45c5b491d90fb2ee08df to your computer and use it in GitHub Desktop.
Make any PHP Exception serializable by flattening complex values in backtrace.
This file contains hidden or 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 | |
function flattenExceptionBacktrace(\Throwable $exception) { | |
if ($exception instanceof \Exception) { | |
$traceProperty = (new \ReflectionClass('Exception'))->getProperty('trace'); | |
} else { | |
$traceProperty = (new \ReflectionClass('Error'))->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)); | |
} | |
}; | |
$previousexception = $exception; | |
do { | |
if ($previousexception === NULL) { | |
break; | |
} | |
$exception = $previousexception; | |
$trace = $traceProperty->getValue($exception); | |
foreach($trace as &$call) { | |
array_walk_recursive($call['args'], $flatten); | |
} | |
$traceProperty->setValue($exception, $trace); | |
} while($previousexception = $exception->getPrevious()); | |
$traceProperty->setAccessible(false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment