77 lines
2.2KB

  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. * ArrayFixture represents arbitrary fixture that can be loaded from PHP files.
  13. *
  14. * @author Mark Jebri <mark.github@yandex.ru>
  15. * @since 2.0
  16. */
  17. class ArrayFixture extends Fixture implements \IteratorAggregate, \ArrayAccess, \Countable
  18. {
  19. use ArrayAccessTrait;
  20. /**
  21. * @var array the data rows. Each array element represents one row of data (column name => column value).
  22. */
  23. public $data = [];
  24. /**
  25. * @var string|boolean the file path or path alias of the data file that contains the fixture data
  26. * to be returned by [[getData()]]. You can set this property to be false to prevent loading any data.
  27. */
  28. public $dataFile;
  29. /**
  30. * Loads the fixture.
  31. *
  32. * The default implementation simply stores the data returned by [[getData()]] in [[data]].
  33. * You should usually override this method by putting the data into the underlying database.
  34. */
  35. public function load()
  36. {
  37. $this->data = $this->getData();
  38. }
  39. /**
  40. * Returns the fixture data.
  41. *
  42. * The default implementation will try to return the fixture data by including the external file specified by [[dataFile]].
  43. * The file should return the data array that will be stored in [[data]] after inserting into the database.
  44. *
  45. * @return array the data to be put into the database
  46. * @throws InvalidConfigException if the specified data file does not exist.
  47. */
  48. protected function getData()
  49. {
  50. if ($this->dataFile === false || $this->dataFile === null) {
  51. return [];
  52. }
  53. $dataFile = Yii::getAlias($this->dataFile);
  54. if (is_file($dataFile)) {
  55. return require($dataFile);
  56. } else {
  57. throw new InvalidConfigException("Fixture data file does not exist: {$this->dataFile}");
  58. }
  59. }
  60. /**
  61. * @inheritdoc
  62. */
  63. public function unload()
  64. {
  65. parent::unload();
  66. $this->data = [];
  67. }
  68. }