Output of the "Get the Symfony project root directory" Symfony snippet

Environment:

  • Strangebuzz Snippet VM: 2.2.1
  • Symfony: 5.1.3

Code execution output:

With the kernel:/var/www-deploy/strangebuzz.com/releases/20200801174757
With the container parameter:/var/www-deploy/strangebuzz.com/releases/20200801174757
<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpKernel\KernelInterface;

/**
 * %docblock1%
 * %docblock2%
 * %docblock3%
 * %docblock4%
 *
 * @property KernelInterface $kernel
 */
trait Snippet6Trait
{
    public function snippet6(): void
    {
        // 1. Using the Kernel (typehint with "KernelInterface")
        //$projectDir = \dirname($kernel->getRootDir()); // <= Symfony 3.2
        $projectDir = $this->kernel->getProjectDir();    // >= Symfony 3.3
        echo 'With the kernel:'.$projectDir.PHP_EOL;

        // 2. Using the "kernel.project_dir" parameter
        $projectDirAlt = $this->getParameter('kernel.project_dir');
        echo 'With the container parameter:'.$projectDir.PHP_EOL;

        if ($projectDir !== $projectDirAlt) {
            throw new \RuntimeException('Project directories are not the same! 💥');
        }

        // Get the template content of this snippet
        $twig = file_get_contents($projectDir.'/src/Controller/Snippet/Snippet6Trait.php');

        echo($twig); // That's it! 😁
    }
}

 Back to the code  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

<?php declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet6Trait
 */
final class Snippet6Test extends KernelTestCase
{
    /**
     * @var string
     */
    private $projectDir;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->projectDir = self::$container->getParameter('kernel.project_dir');
    }

    /**
     * @covers Snippet6Trait::snippet6
     *
     * @see https://www.strangebuzz.com/en/snippets/get-the-symfony-project-root-directory
     */
    public function testSnippet6(): void
    {
        self::assertSame(self::$kernel->getProjectDir(), $this->projectDir);
    }
}