From 96a6c063f23ed7a7165c6c23b26ed1a1508c1b96 Mon Sep 17 00:00:00 2001 From: Daniel Supernault Date: Wed, 4 Dec 2019 19:47:00 -0700 Subject: [PATCH] Update FollowerService --- app/Services/FollowerService.php | 45 ++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/app/Services/FollowerService.php b/app/Services/FollowerService.php index 4c0826114..3a7120ef5 100644 --- a/app/Services/FollowerService.php +++ b/app/Services/FollowerService.php @@ -12,8 +12,8 @@ use App\{ class FollowerService { protected $profile; - protected $follower_prefix; - protected $following_prefix; + static $follower_prefix = 'px:profile:followers-v1.3:'; + static $following_prefix = 'px:profile:following-v1.3:'; public static function build() { @@ -23,35 +23,48 @@ class FollowerService { public function profile(Profile $profile) { $this->profile = $profile; - $this->follower_prefix = config('cache.prefix').':profile:followers:'.$profile->id; - $this->following_prefix = config('cache.prefix').':profile:following:'.$profile->id; + self::$follower_prefix .= $profile->id; + self::$following_prefix .= $profile->id; return $this; } - public function followers($limit = 100, $offset = 0) + public function followers($limit = 100, $offset = 1) { - if(Redis::llen($this->follower_prefix) == 0) { - $followers = $this->profile->followers; + if(Redis::zcard(self::$follower_prefix) == 0) { + $followers = $this->profile->followers()->pluck('profile_id'); $followers->map(function($i) { - Redis::lpush($this->follower_prefix, $i->id); + Redis::zadd(self::$follower_prefix, $i, $i); }); - return $followers; + return Redis::zrevrange(self::$follower_prefix, $offset, $limit); } else { - return Redis::lrange($this->follower_prefix, $offset, $limit); + return Redis::zrevrange(self::$follower_prefix, $offset, $limit); } } - public function following($limit = 100, $offset = 0) + public function following($limit = 100, $offset = 1) { - if(Redis::llen($this->following_prefix) == 0) { - $following = $this->profile->following; + if(Redis::zcard(self::$following_prefix) == 0) { + $following = $this->profile->following()->pluck('following_id'); $following->map(function($i) { - Redis::lpush($this->following_prefix, $i->id); + Redis::zadd(self::$following_prefix, $i, $i); }); - return $following; + return Redis::zrevrange(self::$following_prefix, $offset, $limit); } else { - return Redis::lrange($this->following_prefix, $offset, $limit); + return Redis::zrevrange(self::$following_prefix, $offset, $limit); + } + } + + public static function follows(string $actor, string $target) + { + $key = self::$follower_prefix . $target; + if(Redis::zcard($key) == 0) { + $p = Profile::findOrFail($target); + self::build()->profile($p)->followers(1); + self::build()->profile($p)->following(1); + return (bool) Redis::zrank($key, $actor); + } else { + return (bool) Redis::zrank($key, $actor); } }