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