]> BookStack Code Mirror - bookstack/blob - app/Activity/Notifications/NotificationManager.php
Tests: Updated comment test to account for new editor usage
[bookstack] / app / Activity / Notifications / NotificationManager.php
1 <?php
2
3 namespace BookStack\Activity\Notifications;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Activity\Models\Activity;
7 use BookStack\Activity\Models\Loggable;
8 use BookStack\Activity\Notifications\Handlers\CommentCreationNotificationHandler;
9 use BookStack\Activity\Notifications\Handlers\NotificationHandler;
10 use BookStack\Activity\Notifications\Handlers\PageCreationNotificationHandler;
11 use BookStack\Activity\Notifications\Handlers\PageUpdateNotificationHandler;
12 use BookStack\Users\Models\User;
13
14 class NotificationManager
15 {
16     /**
17      * @var class-string<NotificationHandler>[]
18      */
19     protected array $handlers = [];
20
21     public function handle(Activity $activity, string|Loggable $detail, User $user): void
22     {
23         $activityType = $activity->type;
24         $handlersToRun = $this->handlers[$activityType] ?? [];
25         foreach ($handlersToRun as $handlerClass) {
26             /** @var NotificationHandler $handler */
27             $handler = new $handlerClass();
28             $handler->handle($activity, $detail, $user);
29         }
30     }
31
32     /**
33      * @param class-string<NotificationHandler> $handlerClass
34      */
35     public function registerHandler(string $activityType, string $handlerClass): void
36     {
37         if (!isset($this->handlers[$activityType])) {
38             $this->handlers[$activityType] = [];
39         }
40
41         if (!in_array($handlerClass, $this->handlers[$activityType])) {
42             $this->handlers[$activityType][] = $handlerClass;
43         }
44     }
45
46     public function loadDefaultHandlers(): void
47     {
48         $this->registerHandler(ActivityType::PAGE_CREATE, PageCreationNotificationHandler::class);
49         $this->registerHandler(ActivityType::PAGE_UPDATE, PageUpdateNotificationHandler::class);
50         $this->registerHandler(ActivityType::COMMENT_CREATE, CommentCreationNotificationHandler::class);
51     }
52 }