]> BookStack Code Mirror - bookstack/blob - app/Services/ViewService.php
475500927091bd469e8d4744c47fd5db13be4212
[bookstack] / app / Services / ViewService.php
1 <?php namespace BookStack\Services;
2
3
4 use BookStack\Entity;
5 use BookStack\View;
6
7 class ViewService
8 {
9
10     protected $view;
11     protected $user;
12
13     /**
14      * ViewService constructor.
15      * @param $view
16      */
17     public function __construct(View $view)
18     {
19         $this->view = $view;
20         $this->user = auth()->user();
21     }
22
23     /**
24      * Add a view to the given entity.
25      * @param Entity $entity
26      * @return int
27      */
28     public function add(Entity $entity)
29     {
30         if($this->user === null) return 0;
31         $view = $entity->views()->where('user_id', '=', $this->user->id)->first();
32         // Add view if model exists
33         if ($view) {
34             $view->increment('views');
35             return $view->views;
36         }
37
38         // Otherwise create new view count
39         $entity->views()->save($this->view->create([
40             'user_id' => $this->user->id,
41             'views' => 1
42         ]));
43
44         return 1;
45     }
46
47     /**
48      * Get all recently viewed entities for the current user.
49      * @param int         $count
50      * @param int         $page
51      * @param Entity|bool $filterModel
52      * @return mixed
53      */
54     public function getUserRecentlyViewed($count = 10, $page = 0, $filterModel = false)
55     {
56         if($this->user === null) return collect();
57         $skipCount = $count * $page;
58         $query = $this->view->where('user_id', '=', auth()->user()->id);
59
60         if ($filterModel) $query->where('viewable_type', '=', get_class($filterModel));
61
62         $views = $query->with('viewable')->orderBy('updated_at', 'desc')->skip($skipCount)->take($count)->get();
63         $viewedEntities = $views->map(function ($item) {
64             return $item->viewable()->getResults();
65         });
66         return $viewedEntities;
67     }
68
69
70     /**
71      * Reset all view counts by deleting all views.
72      */
73     public function resetAll()
74     {
75         $this->view->truncate();
76     }
77
78
79 }