diff --git a/src/Rateable.php b/src/Rateable.php index 231fbf2..1ebab07 100755 --- a/src/Rateable.php +++ b/src/Rateable.php @@ -3,6 +3,7 @@ namespace willvincent\Rateable; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Config; trait Rateable { @@ -15,22 +16,38 @@ trait Rateable * * @return Rating */ - public function rate($value, $comment = null) + + private function byUser($user_id = null) { + if(!! $user_id) { + return Auth::id(); + } + + $userClass = Config::get('auth.model'); + if (is_null($userClass)) { + $userClass = Config::get('auth.providers.users.model'); + } + + return (!! $userClass::whereId($user_id)->count())? $user_id: Auth::id(); + } + + public function rate($value, $comment = null, $user_id = null) { + $user_id = $this->byUser($user_id); $rating = new Rating(); $rating->rating = $value; $rating->comment = $comment; - $rating->user_id = Auth::id(); + $rating->user_id = $user_id; $this->ratings()->save($rating); } - public function rateOnce($value, $comment = null) + public function rateOnce($value, $comment = null, $user_id = null) { + $user_id = $this->byUser($user_id); $rating = Rating::query() ->where('rateable_type', '=', $this->getMorphClass()) ->where('rateable_id', '=', $this->id) - ->where('user_id', '=', Auth::id()) + ->where('user_id', '=', $user_id) ->first() ; @@ -68,22 +85,30 @@ public function usersRated() return $this->ratings()->groupBy('user_id')->pluck('user_id')->count(); } - public function userAverageRating() + public function userAverageRating($user_id = null) { - return $this->ratings()->where('user_id', Auth::id())->avg('rating'); + $user_id = $this->byUser($user_id); + return $this->ratings()->where('user_id', $user_id)->avg('rating'); } - public function userSumRating() + public function userSumRating($user_id = null) { - return $this->ratings()->where('user_id', Auth::id())->sum('rating'); + $user_id = $this->byUser($user_id); + return $this->ratings()->where('user_id', $user_id)->sum('rating'); } - public function ratingPercent($max = 5) + public function ratingPercent($max = 5, bool $rounded = false) { $quantity = $this->ratings()->count(); $total = $this->sumRating(); + // return "$total || $quantity"; - return ($quantity * $max) > 0 ? $total / (($quantity * $max) / 100) : 0; + $is_rounded = is_bool($rounded)? $rounded: false; + if($rounded) { + return ($quantity * $max) > 0 ? ceil(($total / ($quantity * $max)) * 100) : 0; + } else { + return ($quantity * $max) > 0 ? $total / (($quantity * $max) / 100) : 0; + } } // Getters