]> BookStack Code Mirror - bookstack/blob - app/Actions/View.php
Merge branch 'master' of https://github.com/awarre/BookStack into awarre-master
[bookstack] / app / Actions / View.php
1 <?php namespace BookStack\Actions;
2
3 use BookStack\Interfaces\Viewable;
4 use BookStack\Model;
5 use Illuminate\Database\Eloquent\Relations\MorphTo;
6
7 /**
8  * Class View
9  * Views are stored per-item per-person within the database.
10  * They can be used to find popular items or recently viewed items
11  * at a per-person level. They do not record every view instance as an
12  * activity. Only the latest and original view times could be recognised.
13  *
14  * @property int $views
15  * @property int $user_id
16  */
17 class View extends Model
18 {
19
20     protected $fillable = ['user_id', 'views'];
21
22     /**
23      * Get all owning viewable models.
24      */
25     public function viewable(): MorphTo
26     {
27         return $this->morphTo();
28     }
29
30     /**
31      * Increment the current user's view count for the given viewable model.
32      */
33     public static function incrementFor(Viewable $viewable): int
34     {
35         $user = user();
36         if (is_null($user) || $user->isDefault()) {
37             return 0;
38         }
39
40         /** @var View $view */
41         $view = $viewable->views()->firstOrNew([
42             'user_id' => $user->id,
43         ], ['views' => 0]);
44
45         $view->forceFill(['views' => $view->views + 1])->save();
46
47         return $view->views;
48     }
49
50     /**
51      * Clear all views from the system.
52      */
53     public static function clearAll()
54     {
55         static::query()->truncate();
56     }
57 }