1 <?php namespace BookStack\Services;
11 protected $permissionService;
14 * ViewService constructor.
16 * @param PermissionService $permissionService
18 public function __construct(View $view, PermissionService $permissionService)
21 $this->user = auth()->user();
22 $this->permissionService = $permissionService;
26 * Add a view to the given entity.
27 * @param Entity $entity
30 public function add(Entity $entity)
32 if ($this->user === null) return 0;
33 $view = $entity->views()->where('user_id', '=', $this->user->id)->first();
34 // Add view if model exists
36 $view->increment('views');
40 // Otherwise create new view count
41 $entity->views()->save($this->view->create([
42 'user_id' => $this->user->id,
50 * Get the entities with the most views.
53 * @param bool|false|array $filterModel
55 public function getPopular($count = 10, $page = 0, $filterModel = false)
57 $skipCount = $count * $page;
58 $query = $this->permissionService->filterRestrictedEntityRelations($this->view, 'views', 'viewable_id', 'viewable_type')
59 ->select('*', 'viewable_id', 'viewable_type', \DB::raw('SUM(views) as view_count'))
60 ->groupBy('viewable_id', 'viewable_type')
61 ->orderBy('view_count', 'desc');
63 if ($filterModel && is_array($filterModel)) {
64 $query->whereIn('viewable_type', $filterModel);
65 } else if ($filterModel) {
66 $query->where('viewable_type', '=', get_class($filterModel));
69 return $query->with('viewable')->skip($skipCount)->take($count)->get()->pluck('viewable');
73 * Get all recently viewed entities for the current user.
76 * @param Entity|bool $filterModel
79 public function getUserRecentlyViewed($count = 10, $page = 0, $filterModel = false)
81 if ($this->user === null) return collect();
83 $query = $this->permissionService
84 ->filterRestrictedEntityRelations($this->view, 'views', 'viewable_id', 'viewable_type');
86 if ($filterModel) $query = $query->where('viewable_type', '=', get_class($filterModel));
87 $query = $query->where('user_id', '=', auth()->user()->id);
89 $viewables = $query->with('viewable')->orderBy('updated_at', 'desc')
90 ->skip($count * $page)->take($count)->get()->pluck('viewable');
95 * Reset all view counts by deleting all views.
97 public function resetAll()
99 $this->view->truncate();