]> BookStack Code Mirror - bookstack/blob - app/Activity/Tools/UserWatchOptions.php
64c5f317f304b732fcd2390ec81bcadd5688b60a
[bookstack] / app / Activity / Tools / UserWatchOptions.php
1 <?php
2
3 namespace BookStack\Activity\Tools;
4
5 use BookStack\Activity\Models\Watch;
6 use BookStack\Activity\WatchLevels;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Users\Models\User;
9 use Illuminate\Database\Eloquent\Builder;
10
11 class UserWatchOptions
12 {
13     public function __construct(
14         protected User $user,
15     ) {
16     }
17
18     public function canWatch(): bool
19     {
20         return $this->user->can('receive-notifications') && !$this->user->isDefault();
21     }
22
23     public function getEntityWatchLevel(Entity $entity): string
24     {
25         $levelValue = $this->entityQuery($entity)->first(['level'])->level ?? -1;
26         return WatchLevels::levelValueToName($levelValue);
27     }
28
29     public function isWatching(Entity $entity): bool
30     {
31         return $this->entityQuery($entity)->exists();
32     }
33
34     public function updateEntityWatchLevel(Entity $entity, string $level): void
35     {
36         $levelValue = WatchLevels::levelNameToValue($level);
37         if ($levelValue < 0) {
38             $this->removeForEntity($entity);
39             return;
40         }
41
42         $this->updateForEntity($entity, $levelValue);
43     }
44
45     protected function updateForEntity(Entity $entity, int $levelValue): void
46     {
47         Watch::query()->updateOrCreate([
48             'watchable_id' => $entity->id,
49             'watchable_type' => $entity->getMorphClass(),
50             'user_id' => $this->user->id,
51         ], [
52             'level' => $levelValue,
53         ]);
54     }
55
56     protected function removeForEntity(Entity $entity): void
57     {
58         $this->entityQuery($entity)->delete();
59     }
60
61     protected function entityQuery(Entity $entity): Builder
62     {
63         return Watch::query()->where('watchable_id', '=', $entity->id)
64             ->where('watchable_type', '=', $entity->getMorphClass())
65             ->where('user_id', '=', $this->user->id);
66     }
67 }