<?php
namespace Retouch\AppBundle\Tests;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\DependencyInjection\Container;
/**
* Class FixturesLoader
*/
class FixturesLoader
{
/**
* @var Application
*/
protected $console;
/**
* @var Container
*/
protected $container;
/**
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
$this->console = new Application($this->container->get('kernel'));
$this->console->setAutoExit(false);
}
/**
* @param array $fixtures
*/
public function loadFixture(array $fixtures = array())
{
$this->runConsole('doctrine:schema:drop --force');
$this->runConsole('doctrine:schema:create');
$loader = new ContainerAwareLoader($this->container);
foreach($fixtures as $fixture){
if($fixture instanceof FixtureInterface){
$loader->addFixture($fixture);
}
}
$fixtures = $loader->getFixtures();
if(!$fixtures){
return;
}
$doctrine = $this->container->get('doctrine');
$em = $doctrine->getManager();
$purger = new ORMPurger($em);
$purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
$executor = new ORMExecutor($em, $purger);
$executor->execute($fixtures, false);
}
/**
* @param $command
* @return int
* @throws \Exception
*/
protected function runConsole($command)
{
$command .= ' --env=test --quiet';
$input = new StringInput($command);
return $this->console->run($input);
}
}