Last active
September 11, 2017 11:08
-
-
Save eghojansu/4ddc4dd0a2759d9e27dce1a322a74af7 to your computer and use it in GitHub Desktop.
Snippet for post Install nelmio/alice di Framework Symfony
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 | |
// src/AppBundle/DataFixtures/ORM/AppFixtures.php | |
namespace AppBundle\DataFixtures\ORM; | |
use Doctrine\Bundle\FixturesBundle\Fixture; | |
use Doctrine\Common\Persistence\ObjectManager; | |
use Nelmio\Alice\Loader\SimpleFileLoader; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
/** | |
* @property ContainerInterface container | |
*/ | |
class AppFixtures extends Fixture | |
{ | |
public function load(ObjectManager $manager) | |
{ | |
/** @var string $fixtureDir */ | |
$fixtureDir = __DIR__ . '/fixtures/'; | |
// fixture files | |
$files = [ | |
'user' => [], | |
'admin' => ['require'=>'user'], | |
'operator' => ['require'=>'user'], | |
]; | |
// fix setup | |
foreach ($files as $fileName => $config) { | |
$config += [ | |
'require'=>[], | |
'required' => false, | |
'items' => [], | |
'parameters' => [], | |
]; | |
$files[$fileName] += $config; | |
if ($config['require']) { | |
$requirements = (array) $config['require']; | |
foreach ($requirements as $requirement) { | |
$files[$requirement]['required'] = true; | |
} | |
} | |
} | |
/** @var SimpleFileLoader $loader */ | |
$loader = $this->container->get('nelmio_alice.file_loader'); | |
// loading objects | |
foreach ($files as $fileName => $config) { | |
$file = $fixtureDir . $fileName . '.yml'; | |
$parameters = $config['require'] ? $files[$config['require']]['parameters'] : []; | |
$parents = $config['require'] ? $files[$config['require']]['items'] : []; | |
$items = $loader | |
->loadFile($file, $parameters, $parents) | |
->getObjects(); | |
foreach ($items as $item) { | |
$manager->persist($item); | |
} | |
if ($config['required']) { | |
$files[$fileName]['items'] = array_merge( | |
$files[$fileName]['items'], | |
$items | |
); | |
} | |
} | |
unset($items, $item, $files); | |
$manager->flush(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment