]> BookStack Code Mirror - bookstack/blob - app/Activity/Notifications/Handlers/CommentCreationNotificationHandler.php
Notifications: Add phpunit test for notification sending
[bookstack] / app / Activity / Notifications / Handlers / CommentCreationNotificationHandler.php
1 <?php
2
3 namespace BookStack\Activity\Notifications\Handlers;
4
5 use BookStack\Activity\Models\Activity;
6 use BookStack\Activity\Models\Comment;
7 use BookStack\Activity\Models\Loggable;
8 use BookStack\Activity\Notifications\Messages\CommentCreationNotification;
9 use BookStack\Activity\Tools\EntityWatchers;
10 use BookStack\Activity\WatchLevels;
11 use BookStack\Entities\Models\Page;
12 use BookStack\Settings\UserNotificationPreferences;
13 use BookStack\Users\Models\User;
14
15 class CommentCreationNotificationHandler extends BaseNotificationHandler
16 {
17     public function handle(Activity $activity, Loggable|string $detail, User $user): void
18     {
19         if (!($detail instanceof Comment)) {
20             throw new \InvalidArgumentException("Detail for comment creation notifications must be a comment");
21         }
22
23         // Main watchers
24         /** @var Page $page */
25         $page = $detail->entity;
26         $watchers = new EntityWatchers($page, WatchLevels::COMMENTS);
27         $watcherIds = $watchers->getWatcherUserIds();
28
29         // Page owner if user preferences allow
30         if (!$watchers->isUserIgnoring($page->owned_by) && $page->ownedBy) {
31             $userNotificationPrefs = new UserNotificationPreferences($page->ownedBy);
32             if ($userNotificationPrefs->notifyOnOwnPageComments()) {
33                 $watcherIds[] = $page->owned_by;
34             }
35         }
36
37         // Parent comment creator if preferences allow
38         $parentComment = $detail->parent()->first();
39         if ($parentComment && !$watchers->isUserIgnoring($parentComment->created_by) && $parentComment->createdBy) {
40             $parentCommenterNotificationsPrefs = new UserNotificationPreferences($parentComment->createdBy);
41             if ($parentCommenterNotificationsPrefs->notifyOnCommentReplies()) {
42                 $watcherIds[] = $parentComment->created_by;
43             }
44         }
45
46         $this->sendNotificationToUserIds(CommentCreationNotification::class, $watcherIds, $user, $detail, $page);
47     }
48 }