<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace qcbase\models;

use Yii;
use yii\helpers\FileHelper;
use yii\db\Query;
use yii\base\ErrorException;

/**
 * 
 * 缓存管理
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Cache extends \yii\base\Object
{
    /**
     * 缓存配置
     *
     * @param $config 缓存配置
     *
     * @key name 缓存名称
     * @key className 缓存模块所在类的名称
     * @key funName 执行缓存的方法名称 默认为setCache
     */
    public static function getConfig()
    {
        $config = [
            'user' => ['name' => '用户', 'className' =>'common\models\User'],
            'department' => ['name' => '部门', 'className' =>'qcbase\models\Department'],
            'config' => ['name' => '站点配置', 'className' =>'qcbase\models\Config'],
            'menu' => ['name' => '菜单', 'className' =>'qcbase\models\Menu'],
            'assets' => ['name' => '发布资源', 'className' =>'qcbase\models\Cache', 'funName' => 'removeAssets'],
        ];
        return $config;
    }

    /**
     * 更新缓存
     */
    public static function update($id)
    {
        $config = self::getConfig();
        if (!isset($config[$id])) {
			throw new ErrorException($id . '不在缓存配置中');
        }
        $module = $config[$id];

        $funName = (isset($module['funName'])) ? $module['funName'] : 'setCache' ;

        try {
            call_user_func([$module['className'], $funName]);
        }
        catch (Exception $e) {
			throw new ErrorException($e->getMessage());
        }

    }

    /**
     * 更新所有缓存
     */
    public static function updateAll()
    {
        $cacheIds = array_keys(static::getConfig());
        foreach ($cacheIds as $id) {
            static::update($id);
        }
    }

    /**
     * 删除前台发布的资源
     */
    public static function removeAssets()
    {
        try {
            $assetsPath = './assets/';
            $handle = opendir($assetsPath);
            while (false !== ($file = readdir($handle))) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                $file = $assetsPath . $file;
                if (is_dir($file)) {
                    \yii\helpers\FileHelper::removeDirectory($file);
                }
                else {
                    unlink($file);
                }
            }
        }
        catch (Exception $e) {
			throw new ErrorException($e->getMessage());
        }
    }


    
}
