Skip to content

Instantly share code, notes, and snippets.

@FAST-JE
Created December 17, 2020 11:56
Show Gist options
  • Save FAST-JE/2c7c201595c2972ecbd59c6a0ebdb5d6 to your computer and use it in GitHub Desktop.
Save FAST-JE/2c7c201595c2972ecbd59c6a0ebdb5d6 to your computer and use it in GitHub Desktop.
<?php
class usersOnline
{
private Redis $redis;
static string $prefix = 'users_online';
static int $userActiveTime = 10;
public function __construct($pathToSock)
{
$this->redis = new Redis();
$this->redis->connect($pathToSock);
$this->redis->select(2);
}
/*
* @param string $userKey
*
* @return void
*/
public function add(string $userKey): void
{
if (!$this->isUserKeyExist($userKey)) {
$this->redis->zAdd(self::$prefix, strtotime("+".self::$userActiveTime." minutes", time()), $userKey);
} else {
$this->redis->zAdd('users_online', ['XX'], strtotime("+".self::$userActiveTime." minutes", time()), $userKey);
}
}
/*
*
* @return int
*/
public function getOnline(): int
{
return $this->redis->zCount(self::$prefix, 0, strtotime("+".self::$userActiveTime." minutes", time()));
}
/*
*
* @return array
*/
public function getOnlineUsers(): array
{
return $this->redis->zRangeByScore(self::$prefix, 0, strtotime("+".self::$userActiveTime." minutes", time()));
}
/*
* @param string $userKey
*
* @return bool
*/
public function isOnline(string $userKey): bool
{
$isOnline = $this->redis->zScore(self::$prefix, $userKey);
if (!empty($isOnline) AND $isOnline > time()) {
return true;
} else {
return false;
}
}
/*
*
* @return void
*/
public function clear(): void
{
$this->redis->zRemRangeByScore(self::$prefix, 0, time()-1);
}
/*
* @param string $userKey
*
* @return bool
*/
private function isUserKeyExist(string $userKey): bool
{
return $this->redis->zScore(self::$prefix, $userKey);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment