Advertisement
fastje

Untitled

Mar 5th, 2021
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.91 KB | None | 0 0
  1. <?php
  2.  
  3. class usersOnline
  4. {
  5.     private Redis $redis;
  6.  
  7.     static string $prefix = 'users_online';
  8.     static int $userActiveTime = 10;
  9.    
  10.     public function __construct($pathToSock)
  11.     {
  12.         $this->redis = new Redis();
  13.         $this->redis->connect($pathToSock);
  14.         $this->redis->select(2);
  15.     }
  16.  
  17.     /*
  18.      * @param string $userKey
  19.      *
  20.      * @return void
  21.      */
  22.     public function add(string $userKey): void
  23.     {
  24.         if (!$this->isUserKeyExist($userKey)) {
  25.             $this->redis->zAdd(self::$prefix, strtotime("+".self::$userActiveTime." minutes", time()), $userKey);
  26.         } else {
  27.             $this->redis->zAdd('users_online', ['XX'], strtotime("+".self::$userActiveTime." minutes", time()), $userKey);
  28.         }
  29.     }
  30.  
  31.     /*
  32.      *
  33.      * @return int
  34.      */
  35.     public function getOnline(): int
  36.     {
  37.         return $this->redis->zCount(self::$prefix, 0, strtotime("+".self::$userActiveTime." minutes", time()));
  38.     }
  39.  
  40.     /*
  41.      *
  42.      * @return array
  43.      */
  44.     public function getOnlineUsers(): array
  45.     {
  46.         return $this->redis->zRangeByScore(self::$prefix, 0, strtotime("+".self::$userActiveTime." minutes", time()));
  47.     }
  48.  
  49.     /*
  50.      * @param string $userKey
  51.      *
  52.      * @return bool
  53.      */
  54.     public function isOnline(string $userKey): bool
  55.     {
  56.         $isOnline = $this->redis->zScore(self::$prefix, $userKey);
  57.         if (!empty($isOnline) AND $isOnline > time()) {
  58.             return true;
  59.         } else {
  60.             return false;
  61.         }
  62.     }
  63.  
  64.     /*
  65.      *
  66.      * @return void
  67.      */
  68.     public function clear(): void
  69.     {
  70.         $this->redis->zRemRangeByScore(self::$prefix, 0, time()-1);
  71.     }
  72.  
  73.     /*
  74.      * @param string $userKey
  75.      *
  76.      * @return bool
  77.      */
  78.     private function isUserKeyExist(string $userKey): bool
  79.     {
  80.         return $this->redis->zScore(self::$prefix, $userKey);
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement