Last active
May 4, 2021 09:09
-
-
Save luismisanchez/2b64fb246e9c48ab9e264cae7f3e9c6e to your computer and use it in GitHub Desktop.
Simple PHP var pretty debugger
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 | |
/** | |
* Simple var pretty debugger | |
* | |
* @param $var | |
* @param false $exit | |
*/ | |
function pre_dump($var, bool $exit = false) { | |
//TODO: Only works if there is a pre_dump() call per line | |
$backtrace = debug_backtrace(); | |
$file = file( $backtrace[0]['file'] ); | |
$line = $backtrace[0]['line'] - 1; | |
preg_match( '#\((.*?)\)#', $file[ $line ], $match ); | |
$var_name = trim( $match[1], '()' ); | |
echo '<pre style="font-size:13px;white-space: pre;">'; | |
if ( is_array( $var ) ) { | |
echo "<span style='font-weight: bold'>+ var_name (array) => " . $var_name . "):</span>\n"; | |
echo "<span style='font-size: 11px;color: #3e44b2'>Called from " . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] . "</span>\n\n"; | |
// var_dump( $var ); | |
print_r($var); | |
} elseif ( is_object($var) ) { | |
echo "<span style='font-weight: bold'>+ var_name (object) => " . $var_name . "):</span>\n"; | |
echo "<span style='font-size: 11px;color: #3e44b2'>Called from " . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] . "</span>\n\n"; | |
print_r( $var ); | |
} elseif (is_string($var)) { | |
$string = json_decode($var, false); | |
//normal string | |
if ( json_last_error() !== JSON_ERROR_NONE ) { | |
echo "<span style='font-weight: bold'>+ var_name (string) => " . $var_name . ":</span>\n"; | |
echo "<span style='font-size: 11px;color: #3e44b2'>Called from " . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] . "</span>\n\n"; | |
echo 'string(' . strlen( $var ) . ') "' . htmlentities( $var ) . "\"\n"; | |
//json string (will return the json_decode output as object) | |
} else { | |
echo "<span style='font-weight: bold'>+ var_name (json_decode output) => " . $var_name . ":</span>\n"; | |
echo "<span style='font-size: 11px;color: #3e44b2'>Called from " . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] . "</span>\n\n"; | |
print_r($string); | |
} | |
} else { | |
echo "<span style='font-weight: bold'>+ var_name => " . $var_name . ":</span>\n"; | |
echo "<span style='font-size: 11px;color: #3e44b2'>Called from " . $backtrace[0]['file'] . ' on line ' . $backtrace[0]['line'] . "</span>\n\n"; | |
var_dump($var); | |
} | |
echo "\n</pre>"; | |
if ($exit) { | |
exit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment