Advertisement
JLChafardet

BaseFixture file

Mar 5th, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\DataFixtures;
  4.  
  5. use Doctrine\Bundle\FixturesBundle\Fixture;
  6. use Doctrine\Common\Persistence\ObjectManager;
  7. use Faker\Factory;
  8. use Faker\Generator;
  9.  
  10. abstract class BaseFixture extends Fixture
  11. {
  12.     /** @var ObjectManager */
  13.     private $manager;
  14.  
  15.     /** @var Generator */
  16.     protected $faker;
  17.  
  18.     /** @var ReferenceIndex */
  19.     private $reeferencesIndex = [];
  20.  
  21.     abstract protected function loadData(ObjectManager $manager);
  22.  
  23.     public function load(ObjectManager $manager)
  24.     {
  25.         $this->manager = $manager;
  26.  
  27.         $this->faker = Factory::create();
  28.  
  29.         $this->loadData($manager);
  30.     }
  31.  
  32.     protected function createMany(string $className, int $count, callable $factory)
  33.     {
  34.         for ($i = 0; $i < $count; $i++) {
  35.             $entity = new $className();
  36.             $factory($entity, $i);
  37.  
  38.             $this->manager->persist($entity);
  39.             // store for usage later as App\Entity\ClassName_#COUNT#
  40.             $this->addReference($className . '_' . $i , $entity);
  41.         }
  42.     }
  43.  
  44.     protected function getRandomReference(string $className) {
  45.         if (!isset($this->referencesIndex[$className])) {
  46.             $this->referencesIndex[$className] = [];
  47.  
  48.             foreach ($this->referenceRepository->getReferences() as $key => $ref) {
  49.                 if (strpos($key, $className.'_') === 0) {
  50.                     $this->referencesIndex[$className][] = $key;
  51.                 }
  52.             }
  53.         }
  54.  
  55.         if (empty($this->referencesIndex[$className])) {
  56.             throw new \Exception(sprintf('Cannot find any references for class "%s"', $className));
  57.         }
  58.  
  59.         $randomReferenceKey = $this->faker->randomElement($this->referencesIndex[$className]);
  60.  
  61.         return $this->getReference($randomReferenceKey);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement