Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement