BaseActiveFixture.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\test;
  8. use Yii;
  9. use yii\base\ArrayAccessTrait;
  10. use yii\base\InvalidConfigException;
  11. /**
  12. * BaseActiveFixture is the base class for fixture classes that support accessing fixture data as ActiveRecord objects.
  13. *
  14. * @author Qiang Xue <[email protected]>
  15. * @since 2.0
  16. */
  17. abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate, \ArrayAccess, \Countable
  18. {
  19. use ArrayAccessTrait;
  20. /**
  21. * @var string the AR model class associated with this fixture.
  22. * @see tableName
  23. */
  24. public $modelClass;
  25. /**
  26. * @var array the data rows. Each array element represents one row of data (column name => column value).
  27. */
  28. public $data = [];
  29. /**
  30. * @var \yii\db\ActiveRecord[] the loaded AR models
  31. */
  32. private $_models = [];
  33. /**
  34. * Returns the AR model by the specified model name.
  35. * A model name is the key of the corresponding data row in [[data]].
  36. * @param string $name the model name.
  37. * @return null|\yii\db\ActiveRecord the AR model, or null if the model cannot be found in the database
  38. * @throws \yii\base\InvalidConfigException if [[modelClass]] is not set.
  39. */
  40. public function getModel($name)
  41. {
  42. if (!isset($this->data[$name])) {
  43. return null;
  44. }
  45. if (array_key_exists($name, $this->_models)) {
  46. return $this->_models[$name];
  47. }
  48. if ($this->modelClass === null) {
  49. throw new InvalidConfigException('The "modelClass" property must be set.');
  50. }
  51. $row = $this->data[$name];
  52. /** @var \yii\db\ActiveRecord $modelClass */
  53. $modelClass = $this->modelClass;
  54. /** @var \yii\db\ActiveRecord $model */
  55. $model = new $modelClass;
  56. $keys = [];
  57. foreach ($model->primaryKey() as $key) {
  58. $keys[$key] = isset($row[$key]) ? $row[$key] : null;
  59. }
  60. return $this->_models[$name] = $modelClass::find($keys);
  61. }
  62. }