brilo-example/tests/Common/DatabaseTestTrait.php

50 lines
1.3 KiB
PHP
Raw Normal View History

2024-08-02 12:13:25 +00:00
<?php
declare(strict_types=1);
namespace App\Tests\Common;
use Doctrine\ORM\EntityManagerInterface;
trait DatabaseTestTrait
{
protected ?EntityManagerInterface $em;
protected function bootDatabase(): void
{
/**
* @var EntityManagerInterface $em
*/
$em = $this->getContainer()->get(EntityManagerInterface::class);
$this->em = $em;
$this->em->getConnection()->executeQuery(<<<EOSQL
DO $$
DECLARE row RECORD;
BEGIN
FOR row IN SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public'
LOOP
EXECUTE format('TRUNCATE TABLE %I CASCADE;',row.table_name);
END LOOP;
END;
$$;
EOSQL);
}
protected function getEntityManager(): EntityManagerInterface
{
if ($this->em === null) {
throw new \LogicException('Database has not been booted yet.');
}
return $this->em;
}
protected function getEntityCount(string $entityClass): int
{
return (int) $this->getEntityManager()->createQuery('SELECT COUNT(e) FROM ' . $entityClass . ' e')->getSingleScalarResult();
}
}