コード例 #1
0
ファイル: FixtureManager.php プロジェクト: bariew/yii2-tools
 /**
  * Gets data from cache or database
  * Truncates tables
  * @return \self
  * @throws \yii\db\Exception
  */
 public static function init()
 {
     if ($data = \Yii::$app->cache->get(static::$cacheKey)) {
         //return static::$data = unserialize($data);
     }
     $dir = \Yii::getAlias(static::$fixturePath);
     MigrationHelper::unsetForeignKeyCheck();
     $files = FileHelper::findFiles($dir, ['only' => ['*.php']]);
     asort($files);
     foreach ($files as $file) {
         $table = preg_replace('/\\d+\\_(.*)/', '$1', basename($file, '.php'));
         \Yii::$app->db->createCommand()->truncateTable($table)->execute();
         if (!($data = (require $file))) {
             continue;
         }
         $modelClass = @$data['modelClass'];
         unset($data['modelClass']);
         foreach ($data as $key => $values) {
             \Yii::$app->db->createCommand()->insert($table, $values)->execute();
             if ($modelClass) {
                 /** @var \yii\db\ActiveRecord $model */
                 $model = new $modelClass($values);
                 static::$data[$table][$key] = $model->hasAttribute('id') ? $model::find()->orderBy(['id' => SORT_DESC])->one() : new $model();
             } else {
                 static::$data[$table][$key] = $values;
             }
         }
     }
     static::update();
     MigrationHelper::setForeignKeyCheck();
     return new static();
 }