<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/3/23
 * Time: 上午9:16
 */

namespace common\helpers;

use yii\db\TableSchema;

class Schema extends \yii\db\oci\Schema
{
    /**
     * 重写载入表结构方法
     * @param string $name
     * @return mixed|null|TableSchema
     */
    protected function loadTableSchema($name)
    {
        $dbName = strtoupper($this->db->username);
        if(strpos($name, $dbName) === 0){
            $tableName = $name;
        } else {
            $tableName = $dbName.'.'.$name;
        }
        $path = \Yii::getAlias('@common/runtime/tableSchema/').$tableName;
        $table = null;
        if(file_exists($path)){
            $cache = file_get_contents($path);
            $table = unserialize($cache);
        }
        if(!$table){
            $oriEnableSlaves = $this->db->enableSlaves;
            $this->db->enableSlaves = false;
            $table = new TableSchema();
            $this->resolveTableNames($table, $name);
            if ($this->findColumns($table)) {
                $this->findConstraints($table);
                $cacheContent = serialize($table);
                file_put_contents($path, $cacheContent);
                $this->db->enableSlaves = $oriEnableSlaves;
                return $table;
            }
            $this->db->enableSlaves = $oriEnableSlaves;
            return null;
        }
        return $table;
    }

    /**
     * 对外公共的方法生成表缓存
     * @param $name
     */
    public function generateTableSchema($name){
        $this->loadTableSchema($name);
    }

    /**
     * 清空表结构缓存
     */
    public function clearTableSchemaCache(){
        $path = \Yii::getAlias('@common/runtime/tableSchema/');
        $waitDel = scandir($path);
        foreach($waitDel as $file){
            if($file === '.gitignore') continue;
            unlink($path.$file);
        }
    }

}