ArrayFixture.php 2.3 KB

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