3 namespace BookStack\Activity\Tools;
5 use BookStack\Activity\Models\Watch;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Users\Models\User;
8 use Illuminate\Database\Eloquent\Builder;
10 class UserWatchOptions
12 protected static array $levelByName = [
20 public function __construct(
25 public function canWatch(): bool
27 return $this->user->can('receive-notifications') && !$this->user->isDefault();
30 public function getEntityWatchLevel(Entity $entity): string
32 $levelValue = $this->entityQuery($entity)->first(['level'])->level ?? -1;
33 return $this->levelValueToName($levelValue);
36 public function isWatching(Entity $entity): bool
38 return $this->entityQuery($entity)->exists();
41 public function updateEntityWatchLevel(Entity $entity, string $level): void
43 $levelValue = $this->levelNameToValue($level);
44 if ($levelValue < 0) {
45 $this->removeForEntity($entity);
49 $this->updateForEntity($entity, $levelValue);
52 protected function updateForEntity(Entity $entity, int $levelValue): void
54 Watch::query()->updateOrCreate([
55 'watchable_id' => $entity->id,
56 'watchable_type' => $entity->getMorphClass(),
57 'user_id' => $this->user->id,
59 'level' => $levelValue,
63 protected function removeForEntity(Entity $entity): void
65 $this->entityQuery($entity)->delete();
68 protected function entityQuery(Entity $entity): Builder
70 return Watch::query()->where('watchable_id', '=', $entity->id)
71 ->where('watchable_type', '=', $entity->getMorphClass())
72 ->where('user_id', '=', $this->user->id);
78 public static function getAvailableLevelNames(): array
80 return array_keys(static::$levelByName);
83 protected static function levelNameToValue(string $level): int
85 return static::$levelByName[$level] ?? -1;
88 protected static function levelValueToName(int $level): string
90 foreach (static::$levelByName as $name => $value) {
91 if ($level === $value) {