FileFixtureTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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\InvalidConfigException;
  10. /**
  11. * FileFixtureTrait provides functionalities for loading data fixture from file.
  12. *
  13. * @author Leandro Guindani Gehlen <leandrogehlen@gmail.com>
  14. * @since 2.0.14
  15. */
  16. trait FileFixtureTrait
  17. {
  18. /**
  19. * @var string the directory path or [path alias](guide:concept-aliases) that contains the fixture data
  20. */
  21. public $dataDirectory;
  22. /**
  23. * @var string|bool the file path or [path alias](guide:concept-aliases) of the data file that contains the fixture data
  24. * to be returned by [[getData()]]. You can set this property to be false to prevent loading any data.
  25. */
  26. public $dataFile;
  27. /**
  28. * Returns the fixture data.
  29. *
  30. * The default implementation will try to return the fixture data by including the external file specified by [[dataFile]].
  31. * The file should return the data array that will be stored in [[data]] after inserting into the database.
  32. *
  33. * @param string $file the data file path
  34. * @param bool $throwException whether to throw exception if fixture data file does not exist.
  35. * @return array the data to be put into the database
  36. * @throws InvalidConfigException if the specified data file does not exist.
  37. */
  38. protected function loadData($file, $throwException = true)
  39. {
  40. if ($file === null || $file === false) {
  41. return [];
  42. }
  43. if (basename($file) === $file && $this->dataDirectory !== null) {
  44. $file = $this->dataDirectory . '/' . $file;
  45. }
  46. $file = Yii::getAlias($file);
  47. if (is_file($file)) {
  48. return require $file;
  49. }
  50. if ($throwException) {
  51. throw new InvalidConfigException("Fixture data file does not exist: {$file}");
  52. }
  53. return [];
  54. }
  55. }