<?php

namespace Base\Tool;

use Redis as Handler;

class Redis
{
    private static $handler;

    public static $allKeys = [
        'promote_history_games' => 'promote_history_games:{promote_id}',    // 会长历史游戏
    ];

    public static function getKey($name, $params = [])
    {
        $realKey = self::$allKeys[$name] ?? null;
        if (is_null($realKey)) {
            throw new \Exception('KEY不存在');
        }
        foreach ($params as $key => $value) {
            $realKey = str_replace('{' . $key . '}', $value, $realKey);
        }
        return $realKey;
    }

    public static function getHandler()
    {
        if(self::$handler == null) {
            self::$handler = self::createHandler();
        }
        return self::$handler;
    }

    private static function createHandler()
    {
        $host = C('REDIS_HOST', null, '127.0.0.1');
        $port = C('REDIS_PORT', null, 6379);
        $timeout = C('REDIS_TIMEOUT', null, 300);
        $auth = C('REDIS_AUTH');
        
        $handler = new Handler();
        $handler->connect($host, $port, $timeout);
        if($auth !== null) {
            $handler->auth($auth);
        }
        return $handler;
    }

    public static function __callStatic($method, $arguments)
    {
        return call_user_func_array([self::getHandler(), $method], $arguments);
    }
}