Output of the "Test if a Doctrine entity is already persisted in the database" %tag% snippet

Environment:

  • Strangebuzz Snippet VM: 1.8.3
  • Symfony: 5.0.4

Code execution output:

false
false

 Back to the code  ≪ showUnitTestButtonLabel ≫  More on Stackoverflow  Random snippet

<?php declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use App\Entity\Article;
use App\Entity\ArticleType;
use App\Repository\ArticleTypeRepository;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet2Trait
 */
final class Snippet2Test extends KernelTestCase
{
    /**
     * @var Registry
     */
    private $doctrine;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->doctrine = self::$container->get('doctrine');
    }

    /**
     * @covers Snippet2Trait::snippet2()
     *
     * @see https://www.strangebuzz.com/en/snippets/test-if-a-doctrine-entity-is-already-persisted-in-the-database
     */
    public function testSnippet2(): void
    {
        $projectDir = self::$container->getParameter('kernel.project_dir');
        $this->assertFileExists($projectDir.'/src/Controller/Snippet/Snippet2Trait.php');

        $manager = $this->doctrine->getManager();
        $article = new Article();
        $this->assertFalse($manager->contains($article));

        $repo = $manager->getRepository(ArticleType::class);
        if (!$repo instanceof ArticleTypeRepository) {
            throw new \RuntimeException('Doctrine repository not found.');
        }
        $article->setType($repo->getArticleType());
        $article->setIsActive(false);
        $manager->persist($article);
        $manager->flush();
        $this->assertTrue($manager->contains($article));

        $manager->remove($article);
        $manager->flush();
        $this->assertFalse($manager->contains($article));
    }
}