Yii Framework Forum: Dynamic Fixture Arrays In Cdbfixturemanager - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Dynamic Fixture Arrays In Cdbfixturemanager new method to allow adding fixtures via coded arrays versus files Rate Topic: -----

#1 User is offline   Jeff Nd4c 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 7
  • Joined: 01-November 11

Posted 17 January 2013 - 04:11 PM

I would like to request adding a simple method to the CDbFixtureManager class that would allow adding fixtures dynamically in code via arrays rather than files. This would allow for having unique fixtures for individual tests or even resetting a fixture during a test. You can, of course, import a fixture file to an array and pass the array to this method, so you can dynamically load in fixture files.

All that is needed is to add the method listed below. The parameters should be pretty obvious.

	public function loadFixtureArray($fixtureName,$tableName,$fixtureArray)
	{
		if($tableName[0]===':')
			$tableName=substr($tableName,1);
		else
		{
			$modelClass=Yii::import($tableName,true);
			$tableName=CActiveRecord::model($modelClass)->tableName();
		}
		if(($prefix=$this->getDbConnection()->tablePrefix)!==null)
			$tableName=preg_replace('/{{(.*?)}}/',$prefix.'\1',$tableName);
		$this->resetTable($tableName);
		
		$rows=array();
		$schema=$this->getDbConnection()->getSchema();
		$builder=$schema->getCommandBuilder();
		$table=$schema->getTable($tableName);
		
		foreach($fixtureArray as $alias=>$row)
		{
			$builder->createInsertCommand($table,$row)->execute();
			$primaryKey=$table->primaryKey;
			if($table->sequenceName!==null)
			{
				if(is_string($primaryKey) && !isset($row[$primaryKey]))
					$row[$primaryKey]=$builder->getLastInsertID($table);
				elseif(is_array($primaryKey))
				{
					foreach($primaryKey as $pk)
					{
						if(!isset($row[$pk]))
						{
							$row[$pk]=$builder->getLastInsertID($table);
							break;
						}
					}
				}
			}
			$rows[$alias]=$row;
		}
		if(is_array($rows) && is_string($fixtureName))
		{
			$this->_rows[$fixtureName]=$rows;
			if(isset($modelClass))
			{
				foreach(array_keys($rows) as $alias)
					$this->_records[$fixtureName][$alias]=$modelClass;
			}
		}
	}

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users