I wrote a simplified VarDumper and wanted to get feedback on areas I can improve on my code. My biggest area of concern is the captureContext method making sure I get the correct file and line depending where dd() is called or if I call the dump method without helper function.
My Response class sets the http response status code.
Here is my helpers.php file
function dd(mixed ...$vars): void
{
$response = new Response;
$var_dumper = new VarDumper($response);
if (array_key_exists(0, $vars) && 1 === count($vars)) {
$var_dumper->dump($vars[0]);
} else {
foreach ($vars as $var) {
$var_dumper->dump($var);
}
}
exit(1);
}
and here is my VarDumper class
namespace App\Support\Debug\VarDumper;
use App\Http\Response;
class VarDumper
{
private ?string $file_path = null;
private ?int $line_number = null;
private Response $response;
public function __construct(Response $response)
{
$this->response = $response;
}
private function captureContext(): void
{
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 20);
$file = $trace[1]['file'];
$line = $trace[1]['line'];
for ($i = 2; $i < 20; ++$i) {
if (isset($trace[$i]['function']) && 'dd' === $trace[$i]['function'])
{
$file = $trace[$i]['file'] ?? $file;
$line = $trace[$i]['line'] ?? $line;
}
}
$this->file_path = ltrim(str_replace(base_path(), '', $file), '/');
$this->line_number = $line;
}
private function formatVar(mixed $var): false|string
{
ob_start();
if (is_string($var) {
echo "<div style="color: blue;">";
echo $var;
echo "</div>";
}
// check for int, float, boolean, arrays
return ob_get_clean();
}
public function dump(mixed $var): void
{
$this->captureContext();
$this->response->setStatusCode(500);
$this->formatVar($var);
}
}