3
* @link https://www.yiiframework.com/
4
* @copyright Copyright (c) 2008 Yii Software LLC
5
* @license https://www.yiiframework.com/license/
10
use yii\base\ArrayAccessTrait;
11
use yii\base\InvalidConfigException;
14
* BaseActiveFixture is the base class for fixture classes that support accessing fixture data as ActiveRecord objects.
16
* For more details and usage information on BaseActiveFixture, see the [guide article on fixtures](guide:test-fixtures).
18
* @author Qiang Xue <qiang.xue@gmail.com>
21
abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate, \ArrayAccess, \Countable
27
* @var string the AR model class associated with this fixture.
31
* @var array the data rows. Each array element represents one row of data (column name => column value).
36
* @var \yii\db\ActiveRecord[] the loaded AR models
38
private $_models = [];
42
* Returns the AR model by the specified model name.
43
* A model name is the key of the corresponding data row in [[data]].
44
* @param string $name the model name.
45
* @return \yii\db\ActiveRecord|null the AR model, or null if the model cannot be found in the database
46
* @throws \yii\base\InvalidConfigException if [[modelClass]] is not set.
48
public function getModel($name)
50
if (!isset($this->data[$name])) {
53
if (array_key_exists($name, $this->_models)) {
54
return $this->_models[$name];
57
if ($this->modelClass === null) {
58
throw new InvalidConfigException('The "modelClass" property must be set.');
60
$row = $this->data[$name];
61
/* @var $modelClass \yii\db\ActiveRecord */
62
$modelClass = $this->modelClass;
64
foreach ($modelClass::primaryKey() as $key) {
65
$keys[$key] = isset($row[$key]) ? $row[$key] : null;
68
return $this->_models[$name] = $modelClass::findOne($keys);
74
* The default implementation simply stores the data returned by [[getData()]] in [[data]].
75
* You should usually override this method by putting the data into the underlying database.
77
public function load()
79
$this->data = $this->getData();
83
* Returns the fixture data.
85
* @return array the data to be put into the database
86
* @throws InvalidConfigException if the specified data file does not exist.
89
protected function getData()
91
return $this->loadData($this->dataFile);
97
public function unload()