Last active
December 18, 2015 15:49
-
-
Save devhelp/5806868 to your computer and use it in GitHub Desktop.
LoaderService based on LoadDataFixturesDoctrineCommand. Basically all logic from the command extracted to reusable service class.
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 | |
namespace Devhelp\Bundle\DataFixturesBundle\Service; | |
use Doctrine\ORM\EntityManager; | |
use Doctrine\Common\DataFixtures\Purger\ORMPurger; | |
use Doctrine\Common\DataFixtures\Executor\ORMExecutor; | |
use Doctrine\Common\DataFixtures\Loader; | |
/** | |
* @author Paweł Barański <pawel.baranski1@gmail.com> | |
*/ | |
class LoaderService | |
{ | |
private $entityManager; | |
private $dataFixturesLoader; | |
public function __construct(EntityManager $entityManager, Loader $dataFixturesLoader) | |
{ | |
$this->entityManager = $entityManager; | |
$this->dataFixturesLoader = $dataFixturesLoader; | |
} | |
public function load($dirOrFile, $append = false, $purgeMode = ORMPurger::PURGE_MODE_DELETE) | |
{ | |
if ($dirOrFile) { | |
$paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile); | |
} else { | |
$paths = array(); | |
} | |
foreach ($paths as $path) { | |
if (is_dir($path)) { | |
$this->dataFixturesLoader->loadFromDirectory($path); | |
} | |
} | |
$fixtures = $this->dataFixturesLoader->getFixtures(); | |
if (!$fixtures) { | |
throw new \InvalidArgumentException( | |
sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths)) | |
); | |
} | |
$purger = new ORMPurger($this->entityManager); | |
$purger->setPurgeMode($purgeMode); | |
$executor = new ORMExecutor($this->entityManager, $purger); | |
$executor->execute($fixtures, $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
parameters: | |
devhelp.data_fixtures.loader.class: Devhelp\Bundle\DataFixturesBundle\Service\LoaderService | |
symfony.data_fixtures.loader.class: Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader | |
services: | |
devhelp.data_fixtures.loader: | |
class: %devhelp.data_fixtures.loader.class% | |
arguments: | |
- '@doctrine.orm.entity_manager' | |
- '@symfony.data_fixtures.loader' | |
symfony.data_fixtures.loader: | |
public: false | |
class: %symfony.data_fixtures.loader.class% | |
arguments: | |
- '@service_container' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment