Skip to content

Instantly share code, notes, and snippets.

@akerouanton
Last active August 29, 2015 14:19
Show Gist options
  • Save akerouanton/d59cafcadff47998b262 to your computer and use it in GitHub Desktop.
Save akerouanton/d59cafcadff47998b262 to your computer and use it in GitHub Desktop.
<?php
namespace Context;
use Behat\Behat\Context\Context as ContextInterface;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Behat\Hook\Scope\BeforeFeatureScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\TaggedNodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
class DatabaseContext implements ContextInterface
{
private static $needSave = false;
private static $backupPath;
protected $container;
public function initialize(array $config, ContainerInterface $container)
{
$this->container = $container;
}
/**
* @BeforeFeature
*/
public static function registerSaveDb(BeforeFeatureScope $event)
{
if (self::hasTag($event->getFeature(), 'save-db')) {
self::$needSave = true;
}
}
/**
* @BeforeScenario
*/
public function saveDb(BeforeScenarioScope $event)
{
if (!self::$needSave) {
return;
}
$backupPath = '/tmp/' . uniqid('', true);
$dbName = $this->getParameter('database_name');
exec(sprintf('mongodump --out %s --db %s 1>/dev/null 2>&1', $backupPath, $dbName));
self::$needSave = false;
self::$backupPath = $backupPath;
}
/**
* @BeforeScenario
*/
public function restoreDbBeforeScenario(BeforeScenarioScope $event, $force = false)
{
if (self::hasTag($event->getScenario(), 'restore-database')) {
$this->restoreDb();
}
}
private function restoreDb()
{
if (!empty(self::$backupPath)) {
exec(sprintf('mongorestore %s 1>/dev/null 2>&1', self::$backupPath));
}
}
/**
* @AfterScenario
*/
public function afterFeature(AfterScenarioScope $event)
{
$this->restoreDb();
}
private static function hasTag(TaggedNodeInterface $node, $tag)
{
return in_array($tag, $node->getTags());
}
private function getParameter($name)
{
if ($this->container->hasParameter($name)) {
return $this->container->getParameter($name);
}
if (null !== $this->getKernel() && $this->getKernel()->getContainer()->hasParameter($name)) {
return $this->getKernel()->getContainer()->getParameter($name);
}
throw new ParameterNotFoundException($name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment