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