Sortie du snippet Doctrine "Tester si une entité Doctrine a déjà été persistée en base"

Environement :

  • Strangebuzz Snippet VM : 2.2.1
  • Symfony : 5.1.3

Sortie du code exécuté :

false
false

 Retour au code  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow  Snippet aléatoire

<?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
{
    private Registry $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');
        self::assertFileExists($projectDir.'/src/Controller/Snippet/Snippet2Trait.php');

        $manager = $this->doctrine->getManager();
        $article = new Article();
        self::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->setActive(false);
        $manager->persist($article);
        $manager->flush();
        self::assertTrue($manager->contains($article));

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