3 namespace BookStack\Activity\Tools;
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;
11 class UserWatchOptions
13 public function __construct(
18 public function canWatch(): bool
20 return $this->user->can('receive-notifications') && !$this->user->isDefault();
23 public function getEntityWatchLevel(Entity $entity): string
25 $levelValue = $this->entityQuery($entity)->first(['level'])->level ?? -1;
26 return WatchLevels::levelValueToName($levelValue);
29 public function isWatching(Entity $entity): bool
31 return $this->entityQuery($entity)->exists();
34 public function updateEntityWatchLevel(Entity $entity, string $level): void
36 $levelValue = WatchLevels::levelNameToValue($level);
37 if ($levelValue < 0) {
38 $this->removeForEntity($entity);
42 $this->updateForEntity($entity, $levelValue);
45 protected function updateForEntity(Entity $entity, int $levelValue): void
47 Watch::query()->updateOrCreate([
48 'watchable_id' => $entity->id,
49 'watchable_type' => $entity->getMorphClass(),
50 'user_id' => $this->user->id,
52 'level' => $levelValue,
56 protected function removeForEntity(Entity $entity): void
58 $this->entityQuery($entity)->delete();
61 protected function entityQuery(Entity $entity): Builder
63 return Watch::query()->where('watchable_id', '=', $entity->id)
64 ->where('watchable_type', '=', $entity->getMorphClass())
65 ->where('user_id', '=', $this->user->id);