|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Application\Command; |
| 6 | + |
| 7 | +use Doctrine\Common\DataFixtures\Executor\ORMExecutor; |
| 8 | +use Doctrine\Common\DataFixtures\Loader; |
| 9 | +use Doctrine\Common\DataFixtures\Purger\ORMPurger; |
| 10 | +use Doctrine\ORM\EntityManager; |
| 11 | +use Symfony\Component\Console\Attribute\AsCommand; |
| 12 | +use Symfony\Component\Console\Command\Command; |
| 13 | +use Symfony\Component\Console\Input\InputInterface; |
| 14 | +use Symfony\Component\Console\Output\OutputInterface; |
| 15 | +use Throwable; |
| 16 | + |
| 17 | +#[AsCommand( |
| 18 | + name: 'application:fixtures:load', |
| 19 | + description: 'Seed the database with data fixtures.', |
| 20 | +)] |
| 21 | +class LoadFixtures extends Command |
| 22 | +{ |
| 23 | + private const array FIXTURES = [ |
| 24 | + // './module/Activity/test/Seeder', |
| 25 | + // './module/Company/test/Seeder', |
| 26 | + './module/Decision/test/Seeder', |
| 27 | + // './module/Education/test/Seeder', |
| 28 | + // './module/Frontpage/test/Seeder', |
| 29 | + // './module/Photo/test/Seeder', |
| 30 | + './module/User/test/Seeder', |
| 31 | + ]; |
| 32 | + |
| 33 | + public function __construct(private readonly EntityManager $entityManager) |
| 34 | + { |
| 35 | + parent::__construct(); |
| 36 | + } |
| 37 | + |
| 38 | + protected function execute( |
| 39 | + InputInterface $input, |
| 40 | + OutputInterface $output, |
| 41 | + ): int { |
| 42 | + $loader = new Loader(); |
| 43 | + $purger = new ORMPurger(); |
| 44 | + $purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE); |
| 45 | + $executor = new ORMExecutor($this->entityManager, $purger); |
| 46 | + |
| 47 | + foreach ($this::FIXTURES as $fixture) { |
| 48 | + $loader->loadFromDirectory($fixture); |
| 49 | + } |
| 50 | + |
| 51 | + $output->writeln('<info>Loading fixtures into the database...</info>'); |
| 52 | + |
| 53 | + $connection = $this->entityManager->getConnection(); |
| 54 | + try { |
| 55 | + // Temporarily disable FK constraint checks. This is necessary because large parts of our database do not have |
| 56 | + // explicit CASCADEs set to prevent data loss when syncing with ReportDB (GEWISDB). |
| 57 | + // The try-catch is necessary to hide some error messages (because the executeStatement). |
| 58 | + $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 0'); |
| 59 | + $executor->execute($loader->getFixtures()); |
| 60 | + $connection->executeStatement('SET FOREIGN_KEY_CHECKS = 1'); |
| 61 | + } catch (Throwable) { |
| 62 | + } |
| 63 | + |
| 64 | + $output->writeln('<info>Loaded fixtures!</info>'); |
| 65 | + |
| 66 | + return Command::SUCCESS; |
| 67 | + } |
| 68 | +} |
0 commit comments