federator/plugins/rediscache.php

124 lines
2.9 KiB
PHP
Raw Normal View History

2024-07-17 11:47:48 +02:00
<?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
{
2024-07-17 21:45:33 +02:00
/**
* 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
*/
2024-07-17 11:47:48 +02:00
private $redis;
/**
* constructor
*/
2024-07-17 11:47:48 +02:00
public function __construct()
{
2024-07-17 21:45:33 +02:00
$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']]);
2024-07-17 11:47:48 +02:00
}
/**
2024-07-17 21:45:33 +02:00
* 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
2024-07-17 11:47:48 +02:00
*/
public function getRemoteUserBySession($_session, $_user)
2024-07-17 11:47:48 +02:00
{
2024-07-17 21:45:33 +02:00
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;
2024-07-17 11:47:48 +02:00
}
/**
2024-07-17 21:45:33 +02:00
* 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)
2024-07-17 11:47:48 +02:00
{
2024-07-17 21:45:33 +02:00
$key = self::createKey('u', $_session, $_user);
$serialized = $user->toJson();
$this->redis->set($key, $serialized);
2024-07-17 11:47:48 +02:00
}
}
namespace Federator;
/**
* Function to initialize plugin
*
* @param \Federator\Main $main main instance
* @return void
*/
function rediscache_load($main)
2024-07-17 11:47:48 +02:00
{
$rc = new Cache\RedisCache();
2024-07-17 11:47:48 +02:00
$main->setCache($rc);
}