Forcing the output of the Symfony debug functions for CLI

Published on 2022-12-13 • Modified on 2022-12-13

This snippet shows how to force the output of the Symfony debug functions for CLI. When using the dd() and dump() functions, the output is automatically adapted to the current context of your call. If you use CLI (commands, for example), the output will be plain text with nice ANSI colours. If you are in a web page context will get friendly HTML to display your debug. Sometimes, it is helpful to force the CLI output, as the context needs to be corrected, for example, when you make CURL calls in your terminal. The PHP SAPI, in this case, is not CLI, and you get an HTLM output that is unreadable in your terminal. That's where this snippet is valuable, just call VarDumperHelper::forceCli() before your dd() or dump() calls, and you are good.
PS: Another option is setting the environment variable VAR_DUMPER_FORMAT=cli, but it didn't work on this project; I just had a blank page. I must investigate this problem.


<?php

declare(strict_types=1);

namespace App\Helper;

use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\VarDumper;

/**
 * Force the CLI output for the dd() and dump() functions. Useful when doing CURL
 * calls in the terminal and wanting to debug.
 */
final class VarDumperHelper
{
    /**
     * @noinspection DisallowWritingIntoStaticPropertiesInspection
     */
    public static function forceCli(): void
    {
        CliDumper::$defaultOutput = 'php://output';
        VarDumper::setHandler(function ($var) {
            $cloner = new VarCloner();
            $dumper = new CliDumper();
            $dumper->dump($cloner->cloneVar($var));
        });
    }
}

 More on Stackoverflow   Read the doc  Random snippet