]> BookStack Code Mirror - bookstack/blobdiff - app/Services/ViewService.php
Closes #55. Allows you to set the primary color.
[bookstack] / app / Services / ViewService.php
index 55e32fe1c89b190f962b0f57c5ab8c76e09fdf77..5b800d939c8c4468bdebe966383007d43ae462f4 100644 (file)
@@ -27,6 +27,7 @@ class ViewService
      */
     public function add(Entity $entity)
     {
+        if($this->user === null) return 0;
         $view = $entity->views()->where('user_id', '=', $this->user->id)->first();
         // Add view if model exists
         if ($view) {
@@ -43,6 +44,29 @@ class ViewService
         return 1;
     }
 
+
+    /**
+     * Get the entities with the most views.
+     * @param int        $count
+     * @param int        $page
+     * @param bool|false $filterModel
+     */
+    public function getPopular($count = 10, $page = 0, $filterModel = false)
+    {
+        $skipCount = $count * $page;
+        $query = $this->view->select('id', 'viewable_id', 'viewable_type', \DB::raw('SUM(views) as view_count'))
+            ->groupBy('viewable_id', 'viewable_type')
+            ->orderBy('view_count', 'desc');
+
+        if($filterModel) $query->where('viewable_type', '=', get_class($filterModel));
+
+        $views = $query->with('viewable')->skip($skipCount)->take($count)->get();
+        $viewedEntities = $views->map(function ($item) {
+            return $item->viewable()->getResults();
+        });
+        return $viewedEntities;
+    }
+
     /**
      * Get all recently viewed entities for the current user.
      * @param int         $count
@@ -52,6 +76,7 @@ class ViewService
      */
     public function getUserRecentlyViewed($count = 10, $page = 0, $filterModel = false)
     {
+        if($this->user === null) return collect();
         $skipCount = $count * $page;
         $query = $this->view->where('user_id', '=', auth()->user()->id);