Debugging a variable with a concise stack trace with the Symfony VarDumper

Published on 2023-04-28 • Modified on 2023-04-28

This snippet shows how to debug a variable with a concise stack trace with the Symfony VarDumper. The debug_print_backtrace() function prints the current stack trace, but unfortunately, it echos it to the standard output without returning it. To have the same result but correctly formatted, you can use this simple trick to capture the output using a dummy exception and the getTraceAsString() function. The Symfony var dumper accurately transforms the lines breaks, so each line is displayed individually.
Original idea by my fellow workmate twitter.com/meyer_baptiste ©.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet253Trait
{
    public function snippet253(Request $request): void
    {
        // I deactivate the debug in prod

        //        dump(
        //            $request->attributes->all(),
        //            (new \Exception())->getTraceAsString()
        //        );

        $debug = <<<'NOWDOC'
Snippet253Trait.php on line 17:
array:9 [▼
  "_route" => "snippet_run"
  "_controller" => "App\Controller\SnippetController::run"
  "_locale" => "en"
  "slug" => "debugging-a-variable-with-a-concise-back-trace-with-the-symfony-vardumper"
  "_route_params" => array:2 [▼
    "_locale" => "en"
    "slug" => "debugging-a-variable-with-a-concise-back-trace-with-the-symfony-vardumper"
  ]
]

Snippet253Trait.php on line 17:
"""
#0 /strangebuzz.com/src/Controller/SnippetController.php(238): App\Controller\SnippetController->snippet253(Object(Symfony\Component\HttpFoundation\Request), Object(App\Repository\ArticleRepository)) ◀
#1 /strangebuzz.com/vendor/symfony/http-kernel/HttpKernel.php(163): App\Controller\SnippetController->run(Object(Symfony\Component\HttpFoundation\Request), 'snippet_run', 'debugging-a-var...', 'en', Object(App\Log\SlackLogger), Object(App\Utility\SpamChecker)) ◀
#2 /strangebuzz.com/vendor/symfony/http-kernel/HttpKernel.php(74): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) ◀
#3 /strangebuzz.com/vendor/symfony/http-kernel/Kernel.php(184): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) ◀
#4 /strangebuzz.com/public/index.php(42): Symfony\Component\HttpKernel\Kernel->handle(Object(Symfony\Component\HttpFoundation\Request))
NOWDOC;

        echo $debug;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!