Skip to content

Instantly share code, notes, and snippets.

@devhelp
Last active December 18, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devhelp/5806868 to your computer and use it in GitHub Desktop.
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.
<?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);
}
}
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