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