Last active
September 1, 2017 14:00
-
-
Save tinker1987/bdc62bbc4c4d57f4fba3eef5c31f805a to your computer and use it in GitHub Desktop.
Allow to load fixtures for integration tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Tests; | |
use Doctrine\Common\DataFixtures\{ | |
Executor\ORMExecutor, FixtureInterface, Purger\ORMPurger, SharedFixtureInterface | |
}; | |
use Doctrine\Common\Persistence\ObjectManager; | |
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader; | |
/** | |
* Class FixtureAwareTestCaseTrait | |
* @package Tests | |
* @author Dmytro Paiareli <[email protected]> | |
*/ | |
trait FixtureAwareTestCaseTrait | |
{ | |
/** | |
* @var ORMExecutor | |
*/ | |
private $fixtureExecutor; | |
/** | |
* @var ContainerAwareLoader | |
*/ | |
private $fixtureLoader; | |
/** | |
* @param FixtureInterface $fixture | |
* @return self | |
*/ | |
protected function addFixture(FixtureInterface $fixture) | |
{ | |
$this->getFixtureLoader()->addFixture($fixture); | |
return $this; | |
} | |
/** | |
* Executes all the fixtures that have been loaded so far. | |
* @param bool $append | |
*/ | |
protected function executeFixtures(bool $append = false) | |
{ | |
$this->getFixtureExecutor()->execute($this->getFixtureLoader()->getFixtures(), $append); | |
} | |
/** | |
* Purges loaded fixtures from DB | |
*/ | |
protected function purgeFixtures() | |
{ | |
$this->getFixtureExecutor()->getPurger()->purge(); | |
} | |
/** | |
* @return ORMExecutor | |
*/ | |
private function getFixtureExecutor() | |
{ | |
if (!$this->fixtureExecutor) { | |
/** | |
* @var \Doctrine\ORM\EntityManager $entityManager | |
*/ | |
$entityManager = self::$kernel->getContainer()->get('doctrine')->getManager(); | |
$this->fixtureExecutor = new class ($entityManager, new ORMPurger($entityManager)) extends ORMExecutor | |
{ | |
/** | |
* @inheritDoc | |
*/ | |
public function load(ObjectManager $manager, FixtureInterface $fixture) | |
{ | |
if ($fixture instanceof SharedFixtureInterface) { | |
$fixture->setReferenceRepository($this->referenceRepository); | |
} | |
$fixture->load($manager); | |
} | |
}; | |
} | |
return $this->fixtureExecutor; | |
} | |
/** | |
* @return ContainerAwareLoader | |
*/ | |
private function getFixtureLoader() | |
{ | |
if (!$this->fixtureLoader) { | |
$this->fixtureLoader = new ContainerAwareLoader(self::$kernel->getContainer()); | |
} | |
return $this->fixtureLoader; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test case class should extends
Symfony\Bundle\FrameworkBundle\Test\KernelTestCase
to able get access to service container.