1 <?php namespace BookStack\Services;
12 protected $restrictionService;
15 * ViewService constructor.
17 * @param RestrictionService $restrictionService
19 public function __construct(View $view, RestrictionService $restrictionService)
22 $this->user = auth()->user();
23 $this->restrictionService = $restrictionService;
27 * Add a view to the given entity.
28 * @param Entity $entity
31 public function add(Entity $entity)
33 if ($this->user === null) return 0;
34 $view = $entity->views()->where('user_id', '=', $this->user->id)->first();
35 // Add view if model exists
37 $view->increment('views');
41 // Otherwise create new view count
42 $entity->views()->save($this->view->create([
43 'user_id' => $this->user->id,
52 * Get the entities with the most views.
55 * @param bool|false $filterModel
57 public function getPopular($count = 10, $page = 0, $filterModel = false)
59 $skipCount = $count * $page;
60 $query = $this->restrictionService->filterRestrictedEntityRelations($this->view, 'views', 'viewable_id', 'viewable_type')
61 ->select('id', 'viewable_id', 'viewable_type', \DB::raw('SUM(views) as view_count'))
62 ->groupBy('viewable_id', 'viewable_type')
63 ->orderBy('view_count', 'desc');
65 if ($filterModel) $query->where('viewable_type', '=', get_class($filterModel));
67 $views = $query->with('viewable')->skip($skipCount)->take($count)->get();
68 $viewedEntities = $views->map(function ($item) {
69 return $item->viewable()->getResults();
71 return $viewedEntities;
75 * Get all recently viewed entities for the current user.
78 * @param Entity|bool $filterModel
81 public function getUserRecentlyViewed($count = 10, $page = 0, $filterModel = false)
83 if ($this->user === null) return collect();
84 $skipCount = $count * $page;
85 $query = $this->restrictionService
86 ->filterRestrictedEntityRelations($this->view, 'views', 'viewable_id', 'viewable_type');
88 if ($filterModel) $query = $query->where('viewable_type', '=', get_class($filterModel));
89 $query = $query->where('user_id', '=', auth()->user()->id);
91 $views = $query->with('viewable')->orderBy('updated_at', 'desc')->skip($skipCount)->take($count)->get();
92 $viewedEntities = $views->map(function ($item) {
93 return $item->viewable;
95 return $viewedEntities;
100 * Reset all view counts by deleting all views.
102 public function resetAll()
104 $this->view->truncate();