**/ namespace Federator\Cache; /** * Caching class using redis */ class RedisCache implements Cache { /** * config data * * @var array $config */ private $config; /** * connection to redis open flag * * @var bool $connected */ private $connected = false; /** * connection handle * * @var \Redis $redis */ private $redis; /** * user cache time to life * * @var int time to life in secons */ private $userTTL; /** * constructor */ public function __construct() { $config = parse_ini_file('../rediscache.ini'); if ($config !== false) { $this->config = $config; $this->userTTL = array_key_exists('userttl', $config) ? intval($config['userttl'], 10) : 60; } } /** * connect to redis * @return void */ private function connect() { $this->redis = new \Redis(); $this->redis->pconnect($this->config['host'], intval($this->config['port'], 10)); // @phan-suppress-next-line PhanTypeMismatchArgumentInternalProbablyReal $this->redis->auth([$this->config['username'], $this->config['password']]); } /** * create key from session and user * * @param string $prefix prefix to create name spaces * @param string $_session session id * @param string $_user user/profile name * @return string key */ private static function createKey($prefix, $_session, $_user) { $key = $prefix . '_'; $key .= md5($_session . $_user); return $key; } /** * get remote user by given session * * @param string $_session session id * @param string $_user user/profile name * @return \Federator\Data\User | false */ public function getRemoteUserBySession($_session, $_user) { if (!$this->connected) { $this->connect(); } $key = self::createKey('u', $_session, $_user); $data = $this->redis->get($key); if ($data === false) { return false; } $user = \Federator\Data\User::createFromJson($data); return $user; } /** * save remote user by given session * * @param string $_session session id * @param string $_user user/profile name * @param \Federator\Data\User $user user data * @return void */ public function saveRemoteUserBySession($_session, $_user, $user) { $key = self::createKey('u', $_session, $_user); $serialized = $user->toJson(); $this->redis->setEx($key, $this->userTTL, $serialized,); } } namespace Federator; /** * Function to initialize plugin * * @param \Federator\Main $main main instance * @return void */ function rediscache_load($main) { $rc = new Cache\RedisCache(); $main->setCache($rc); }