Skip to content

Instantly share code, notes, and snippets.

@tPl0ch
Created November 23, 2012 16:23
Show Gist options
  • Save tPl0ch/4136336 to your computer and use it in GitHub Desktop.
Save tPl0ch/4136336 to your computer and use it in GitHub Desktop.
A Symfony2 TestCase base class that autoloads ODM Mongo Fixtures
<?php
namespace RC\FixtureAutoLoadBundle\Test;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\Common\DataFixtures\Executor\MongoDBExecutor;
use Doctrine\Common\DataFixtures\Purger\MongoDBPurger;
/**
* This TestCase enables to load fixtures automagically if you pass an array of
* bundles. Depends on the DoctrineDataFixturesBundle.
*/
abstract class ODMFixtureTestCase extends WebTestCase
{
/**
* Add the Bundlenames from which to load the fixture.
* To be overriden in your child classes.
*
* @staticvar array
*/
public static $fixtures = array();
/**
* Holds the document manager instance
*
* @staticvar Doctrine\ODM\MongoDB\DocumentManager
*/
public static $dm;
/**
* Autoloads the fixtures passed in the static array $fixtures
*
* @param array $options The options
* @param array $kernelOptions The options to pass to `WebTestCase::createKernel()`
*
* @throws \InvalidArgumentException
*
* TODO: Add support for other Entity/Document managers
*/
protected static function loadFixtures(array $options = array(), array $kernelOptions = array())
{
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
static::$kernel = static::createKernel($kernelOptions);
static::$kernel->boot();
static::$dm = static::$kernel->getContainer()
->get('doctrine.odm.mongodb.document_manager');
$paths = array();
foreach (static::$fixtures as $bundle) {
$bundle = static::$kernel->getBundle($bundle, true);
if (!$bundle) {
continue;
}
$paths[] = $bundle->getPath().'/DataFixtures/MongoDB';
}
$loader = new ContainerAwareLoader(static::$kernel->getContainer());
foreach ($paths as $path) {
if (is_dir($path)) {
$loader->loadFromDirectory($path);
}
}
$fixtures = $loader->getFixtures();
if (!$fixtures) {
throw new \InvalidArgumentException(
sprintf('Could not find any fixtures to load in: %s', "\n\n- ".implode("\n- ", $paths))
);
}
$purger = new MongoDBPurger(static::$dm);
$executor = new MongoDBExecutor(static::$dm, $purger);
$executor->execute($fixtures, false);
}
/**
* Purges the db and shuts down the kernel
*/
protected function tearDown()
{
$purger = new MongoDBPurger(static::$dm);
$purger->purge();
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment