1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95:
<?php
namespace Kazuakim\Reddish;
class Clients extends \Redis
{
protected $config;
private static $_defaultConfig = [
'host' => null,
'port' => 6379,
'timeout' => 0.0,
'reserved' => null,
'retry_interval' => null,
'persistent_id' => '',
'password' => null,
'serializer' => \Redis::SERIALIZER_NONE,
'persistent' => false,
];
public function __construct(array $config)
{
$this->config = array_merge(self::$_defaultConfig, $config);
$this->connection();
}
public function connection()
{
if (!$this->config['persistent'] && !@$this->connect($this->config['host'], $this->config['port'], $this->config['timeout'], $this->config['reserved'], $this->config['retry_interval'])) {
throw new ReddishException('connect errored.');
} elseif (!@$this->pconnect($this->config['host'], $this->config['port'], $this->config['timeout'], $this->config['persistent_id'], $this->config['retry_interval'])) {
throw new ReddishException('pconnect errored.');
}
if (0 < strlen($this->config['password']) && !$this->auth($this->config['password'])) {
throw new ReddishException('auth errored.');
}
$this->setSerializer($this->config['serializer']);
}
public function setSerializer($serializer)
{
assert(in_array($serializer, self::_getSerializerArray(), true), 'serializer setting errored.');
if (!$this->setOption(\Redis::OPT_SERIALIZER, $serializer)) {
throw new ReddishException('serializer errored.');
}
}
public function close()
{
if ($this->config['persistent']) {
parent::close();
}
}
public function ping()
{
try {
parent::ping();
} catch (\RedisException $e) {
throw new ReddishException($e->getMessage());
}
}
private static function _getSerializerArray(): array
{
if (extension_loaded('igbinary') === false) {
return [
\Redis::SERIALIZER_NONE,
\Redis::SERIALIZER_PHP,
];
}
return [
\Redis::SERIALIZER_NONE,
\Redis::SERIALIZER_PHP,
\Redis::SERIALIZER_IGBINARY,
];
}
}