Check if the Symfony debug mode is activated

Published on 2019-07-22 • Modified on 2019-07-22

Sometimes it's useful to know if the debug mode is activated. (with the famous debug bar) For example for a batch process, if it is on, perhaps you only want to process some rows instead of processing the whole table. To get the flag you need to get the kernel instance and call the isDebug function.


<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Entity\ArticleRepository;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * I am using a PHP trait in order 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 Snippet33Trait
{
    public function snippet33(): void
    {
        if (!$this->articleRepo instanceof ArticleRepository) {
            throw new \RuntimeException("Houston, we've got a problem! 💥");
        }

        if (!$this->kernel instanceof KernelInterface) {
            throw new InvalidTypeException("Houston, we've got a problem! 💥");
        }

        echo $this->kernel->isDebug() ? 'Debug is ✅' : 'Debug is ❌';

        $maxToProcess = $this->kernel->isDebug() ? 2 : null; // null in this context means to maximum
        $snippets = $this->articleRepo->findSnippetsForLang('en', null, $maxToProcess);

        echo PHP_EOL.sprintf('%d snippets to process! 🏭', count($snippets));

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc