]> BookStack Code Mirror - bookstack/blob - app/Actions/Webhook.php
55bc855cedeaea45c203e3730cd9f52154f3e113
[bookstack] / app / Actions / Webhook.php
1 <?php
2
3 namespace BookStack\Actions;
4
5 use BookStack\Interfaces\Loggable;
6 use Illuminate\Database\Eloquent\Collection;
7 use Illuminate\Database\Eloquent\Factories\HasFactory;
8 use Illuminate\Database\Eloquent\Model;
9 use Illuminate\Database\Eloquent\Relations\HasMany;
10
11 /**
12  * @property int $id
13  * @property string $name
14  * @property string $endpoint
15  * @property Collection $trackedEvents
16  */
17 class Webhook extends Model implements Loggable
18 {
19     protected $fillable = ['name', 'endpoint'];
20
21     use HasFactory;
22
23     /**
24      * Define the tracked event relation a webhook.
25      */
26     public function trackedEvents(): HasMany
27     {
28         return $this->hasMany(WebhookTrackedEvent::class);
29     }
30
31     /**
32      * Update the tracked events for a webhook from the given list of event types.
33      */
34     public function updateTrackedEvents(array $events): void
35     {
36         $this->trackedEvents()->delete();
37
38         $eventsToStore = array_intersect($events, array_values(ActivityType::all()));
39         if (in_array('all', $events)) {
40             $eventsToStore = ['all'];
41         }
42
43         $trackedEvents = [];
44         foreach ($eventsToStore as $event) {
45             $trackedEvents[] = new WebhookTrackedEvent(['event' => $event]);
46         }
47
48         $this->trackedEvents()->saveMany($trackedEvents);
49     }
50
51     /**
52      * Check if this webhook tracks the given event.
53      */
54     public function tracksEvent(string $event): bool
55     {
56         return $this->trackedEvents->pluck('event')->contains($event);
57     }
58
59     /**
60      * Get a URL for this webhook within the settings interface.
61      */
62     public function getUrl(string $path = ''): string
63     {
64         return url('/settings/webhooks/' . $this->id . '/' . ltrim($path, '/'));
65     }
66
67     /**
68      * Get the string descriptor for this item.
69      */
70     public function logDescriptor(): string
71     {
72         return "({$this->id}) {$this->name}";
73     }
74 }