<?php

namespace tw\redis;

use think\facade\Config;

/**
 * 另一个 Redis 客户端，另一个是 Cache 使用
 */
class TwRedis
{

    protected static $inst;

    protected $handle;

    protected function __construct($options)
    {
        if (extension_loaded('redis')) {
            $this->handle = new \Redis;

            if ($options['persistent']) {
                $this->handle->pconnect($options['host'], $options['port'], $options['timeout'], 'tw_persistent_id' . $options['select']);
            } else {
                $this->handle->connect($options['host'], $options['port'], $options['timeout']);
            }
            if ('' != $options['password']) {
                $this->handle->auth($options['password']);
            }
            if (0 != $options['select']) {
                $this->handle->select($options['select']);
            }
        } else {
            throw new \BadFunctionCallException('not support: redis');
        }
    }

    public static function instance()
    {
        if (is_null(self::$inst)) {
            $options = Config::get('redis', []);
            self::$inst = new static($options);
        }
        return self::$inst;
    }

    public static function __callStatic($name, $arguments)
    {
        return self::instance()->handle->{$name}(...$arguments);
    }
}
