Skip to content

Instantly share code, notes, and snippets.

@mattsenior
Last active December 15, 2015 11:58
Show Gist options
  • Save mattsenior/5256730 to your computer and use it in GitHub Desktop.
Save mattsenior/5256730 to your computer and use it in GitHub Desktop.
Just a very basic snippet of purging entities and loading fixtures with Nelmio\Alice within a BehatContext
<?php
namespace Context;
use Behat\Behat\Context\BehatContext,
Behat\Symfony2Extension\Context\KernelAwareInterface;
use Nelmio\Alice as Fixtures;
// ...
/**
* Data writing and reading context
*/
class DataContext extends BehatContext implements KernelAwareInterface
{
// ...
/**
* E.g. ‘Given there are pages in the database’ loads pages.yml, and
* ‘Given there are users and tasks in the database’ loads users_and_tasks.yml.
*
* Tables are purged as new entities are loaded in.
*
* @Given /^there (?:is|are) (.+) in the database$/
*/
public function loadFixtures($fixtures)
{
$fixtures = preg_replace(array('/[^\w\s]/', '/\s+/'),
array('', '_'),
$fixtures);
$loader = new Fixtures\Loader\Yaml;
$objects = $loader->load($this->getFixturesDir().$fixtures.'.yml');
$em = $this->getEntityManager();
$purged = array();
foreach ($objects as $object)
{
$class = get_class($object);
if (in_array($class, $purged))
{
continue 1;
}
// Delete $class
$q = $em->createQuery(sprintf('DELETE FROM %s', $class));
$q->execute();
$purged[] = $class;
}
$persister = new Fixtures\ORM\Doctrine($em);
$persister->persist($objects);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment