Skip to content

Commit

Permalink
Merge pull request #1 from customd/webhook-based-payload-configuration
Browse files Browse the repository at this point in the history
feat: webhook models can optionally modify payloads individually
  • Loading branch information
phpsa authored Jul 17, 2022
2 parents cc3b134 + dbec6f7 commit ea1a17e
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 5 deletions.
15 changes: 14 additions & 1 deletion src/Models/Contracts/WebhookEndpointContract.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,22 @@

interface WebhookEndpointContract
{

/**
* Get the events relationship
*/
public function events(): HasMany;

/**
* Get the webhook payload, customised for this specific endpoint.
*
* @return array
*/
public function getWebhookPayload(WebhookEventContract $event, array $payload): array;

/**
* Should we allow this event to deliver webhooks?
*
* @return bool
*/
public function shouldDeliverWebhook(WebhookEventContract $event, array $payload): bool;
}
2 changes: 1 addition & 1 deletion src/Models/Traits/HasWebhookEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ trait HasWebhookEndpoint
{
public function endpoint(): BelongsTo
{
return $this->belongsTo(WebhookEndpoint::class, 'webhook_endpoint_id');
return $this->belongsTo(config('webhook-registry.models.endpoint'), 'webhook_endpoint_id');
}
}
15 changes: 13 additions & 2 deletions src/Models/Traits/HasWebhookEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

namespace CustomD\WebhookRegistry\Models\Traits;

use CustomD\WebhookRegistry\Models\WebhookEvent;
use Illuminate\Database\Eloquent\Builder;
use CustomD\WebhookRegistry\Models\WebhookEvent;
use Illuminate\Database\Eloquent\Relations\HasMany;
use CustomD\WebhookRegistry\Models\Contracts\WebhookEventContract;

trait HasWebhookEvent
{
Expand All @@ -19,6 +20,16 @@ function ($endpoint) {

public function events(): HasMany
{
return $this->hasMany(WebhookEvent::class);
return $this->hasMany(config('webhook-registry.models.event'));
}

public function getWebhookPayload(WebhookEventContract $event, array $payload): array
{
return $payload;
}

public function shouldDeliverWebhook(WebhookEventContract $event, array $payload): bool
{
return true;
}
}
7 changes: 6 additions & 1 deletion src/WebhookRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,12 @@ public function trigger(string $event, array $payload = []): void
}

foreach ($events as $event) {
$this->dispatchWebhook($event->endpoint, $payload);

if (! $event->endpoint->shouldDeliverWebhook($event, $payload)) {
continue;
}

$this->dispatchWebhook($endpoint, $endpoint->getWebhookPayload($event, $payload));
}
}

Expand Down

0 comments on commit ea1a17e

Please sign in to comment.