]> BookStack Code Mirror - bookstack/blob - app/Services/ViewService.php
Added view count tracking with personalised lists
[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         $view = $entity->views()->where('user_id', '=', $this->user->id)->first();
31         // Add view if model exists
32         if ($view) {
33             $view->increment('views');
34             return $view->views;
35         }
36
37         // Otherwise create new view count
38         $entity->views()->save($this->view->create([
39             'user_id' => $this->user->id,
40             'views' => 1
41         ]));
42
43         return 1;
44     }
45
46     /**
47      * Get all recently viewed entities for the current user.
48      * @param int         $count
49      * @param int         $page
50      * @param Entity|bool $filterModel
51      * @return mixed
52      */
53     public function getUserRecentlyViewed($count = 10, $page = 0, $filterModel = false)
54     {
55         $skipCount = $count * $page;
56         $query = $this->view->where('user_id', '=', auth()->user()->id);
57
58         if ($filterModel) $query->where('viewable_type', '=', get_class($filterModel));
59
60         $views = $query->with('viewable')->orderBy('updated_at', 'desc')->skip($skipCount)->take($count)->get();
61         $viewedEntities = $views->map(function ($item) {
62             return $item->viewable()->getResults();
63         });
64         return $viewedEntities;
65     }
66
67
68     /**
69      * Reset all view counts by deleting all views.
70      */
71     public function resetAll()
72     {
73         $this->view->truncate();
74     }
75
76
77 }