Last active
October 18, 2023 19:23
-
-
Save lavoiesl/77375da08b3274aa6440 to your computer and use it in GitHub Desktop.
Load Doctrine Fixtures when using Migrations in Symfony: AbstractFixtureMigration
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 | |
use Doctrine\Common\DataFixtures\Executor\ORMExecutor; | |
use Doctrine\Common\DataFixtures\Purger\ORMPurger; | |
use Doctrine\DBAL\Migrations\AbstractMigration; | |
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader as Loader; | |
use Symfony\Component\Console\Output\ConsoleOutput; | |
use Symfony\Component\DependencyInjection\ContainerAwareInterface; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
abstract class AbstractFixtureMigration extends AbstractMigration implements ContainerAwareInterface | |
{ | |
use FixtureMigrationTrait; | |
private $container; | |
public function setContainer(ContainerInterface $container = null) | |
{ | |
$this->container = $container; | |
} | |
public function loadFixtures(array $fixtures, $append = true) | |
{ | |
$em = $this->container->get('doctrine.orm.entity_manager'); | |
$loader = new Loader($this->container); | |
array_map(array($loader, 'addFixture'), $fixtures); | |
$purger = null; | |
if ($append === false) { | |
$purger = new ORMPurger($em); | |
$purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE); | |
} | |
$executor = new ORMExecutor($em, $purger); | |
$output = new ConsoleOutput; | |
$executor->setLogger(function($message) use ($output) { | |
$output->writeln(sprintf(' <comment>></comment> <info>%s</info>', $message)); | |
}); | |
$executor->execute($loader->getFixtures(), $append); | |
} | |
} |
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 | |
use Doctrine\DBAL\Schema\Schema; | |
use AcmeBundle\DataFixtures\ORM as Fixtures; | |
class Version1 extends AbstractFixtureMigration | |
{ | |
public function up(Schema $schema) | |
{ | |
// ... | |
} | |
public function down(Schema $schema) | |
{ | |
// ... | |
} | |
public function postUp(Schema $schema) | |
{ | |
$this->loadFixtures(array( | |
new Fixtures\LoadMyData, | |
new Fixtures\LoadMyOtherData, | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great! It is missing FixtureMigrationTrait however it is unused anyway, just removed it.