federator/plugins/rediscache.php

124 lines
2.9 KiB
PHP

<?php
/**
* SPDX-FileCopyrightText: 2024 Sascha Nitsch (grumpydeveloper) https://contentnation.net/@grumpydevelop
* SPDX-License-Identifier: GPL-3.0-or-later
*
* @author Sascha Nitsch <grumpydevelop@contentnation.net>
**/
namespace Federator\Cache;
/**
* Caching class using redis
*/
class RedisCache implements Cache
{
/**
* config data
*
* @var array<string, mixed> $config
*/
private $config;
/**
* connection to redis open flag
*
* @var bool $connected
*/
private $connected = false;
/**
* connection handle
*
* @var \Redis $redis
*/
private $redis;
/**
* constructor
*/
public function __construct()
{
$config = parse_ini_file('../rediscache.ini');
if ($config !== false) {
$this->config = $config;
}
}
/**
* 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->set($key, $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);
}