Skip to content

Instantly share code, notes, and snippets.

@b00gizm
Created November 13, 2009 14:20
Show Gist options
  • Save b00gizm/233855 to your computer and use it in GitHub Desktop.
Save b00gizm/233855 to your computer and use it in GitHub Desktop.
<?php
/**
* This class provides easy access to your fixture data with Propel as ORM.
*
* I tried to use a similar approach like in Ruby on Rails.
* See: http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures
*
* @package default
* @author b00giZm
**/
class sfPropelObjectFromFixtureLoader
{
protected $filename = null;
protected $fixtureData = null;
/**
* Loads the fixture data into an array
*
* @see sfYaml.class.php
* @throws InvalidArgumentException
**/
protected function loadYml()
{
if (!is_file($this->filename))
{
throw new InvalidArgumentException(sprintf("File '%s' does not exist", $this->filename));
}
$this->fixtureData = sfYaml::load($this->filename);
}
/**
* Constructor
*
* @param string $filename The path to your fixtures file
**/
public function __construct($filename)
{
$this->filename = $filename;
}
/**
* Getter fixtureData
*
* @return array The fixture Data as array
**/
public function getFixtureData()
{
return $this->fixtureData;
}
/**
* Setter filename
*
* @param string $filename The path to your fixtures file
**/
public function setFilename($filename)
{
$this->filename = $filename;
}
/**
* Getter filename
*
* @return string The path to your fixtures file
**/
public function getFilename()
{
return $this->filename;
}
/**
* This is where the magic happens
* The method tries to load the object data by a named fixture
* and returns the (Propel) object
*
* @param string $name The named fixture
* @return mixed The Propel object or NULL if loading fails
**/
public function load($name)
{
// Loads the .yml file into an array
$this->loadYml();
if (!is_null($this->fixtureData))
{
$keys = array_keys($this->fixtureData);
$objectName = $keys[0];
$allFixtures = $this->fixtureData[$objectName];
$keys = array_keys($allFixtures);
if (($idx = array_search($name, $keys)) === false)
{
return null;
}
$c = new Criteria();
$c->setOffset($idx);
return call_user_func(array($objectName.'Peer', 'doSelectOne'), $c);
}
return null;
}
}
// Sample data / fixture 'article.yml'
Article:
first_article:
# ...
second_article:
# ...
// Usage
$l = new sfPropelObjectFromFixtureLoader('/path/to/article.yml');
$firstArticle = $l->load('first_article');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment