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