Added option to send orphan visits to webhooks

This commit is contained in:
Alejandro Celaya
2021-10-09 10:53:21 +02:00
parent c718b94937
commit d16fda3f16
8 changed files with 102 additions and 15 deletions

View File

@@ -16,6 +16,7 @@ use Shlinkio\Shlink\Common\Rest\DataTransformerInterface;
use Shlinkio\Shlink\Core\Entity\Visit;
use Shlinkio\Shlink\Core\EventDispatcher\Event\VisitLocated;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Shlinkio\Shlink\Core\Options\WebhookOptions;
use Throwable;
use function Functional\map;
@@ -26,8 +27,7 @@ class NotifyVisitToWebHooks
private ClientInterface $httpClient,
private EntityManagerInterface $em,
private LoggerInterface $logger,
/** @var string[] */
private array $webhooks,
private WebhookOptions $webhookOptions,
private DataTransformerInterface $transformer,
private AppOptions $appOptions,
) {
@@ -35,7 +35,7 @@ class NotifyVisitToWebHooks
public function __invoke(VisitLocated $shortUrlLocated): void
{
if (empty($this->webhooks)) {
if (! $this->webhookOptions->hasWebhooks()) {
return;
}
@@ -50,6 +50,10 @@ class NotifyVisitToWebHooks
return;
}
if ($visit->isOrphan() && ! $this->webhookOptions->notifyOrphanVisits()) {
return;
}
$requestOptions = $this->buildRequestOptions($visit);
$requestPromises = $this->performRequests($requestOptions, $visitId);
@@ -78,7 +82,7 @@ class NotifyVisitToWebHooks
private function performRequests(array $requestOptions, string $visitId): array
{
return map(
$this->webhooks,
$this->webhookOptions->webhooks(),
fn (string $webhook): PromiseInterface => $this->httpClient
->requestAsync(RequestMethodInterface::METHOD_POST, $webhook, $requestOptions)
->otherwise(fn (Throwable $e) => $this->logWebhookFailure($webhook, $visitId, $e)),

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Options;
use Laminas\Stdlib\AbstractOptions;
class WebhookOptions extends AbstractOptions
{
protected $__strictMode__ = false; // phpcs:ignore
private array $visitsWebhooks = [];
private bool $notifyOrphanVisitsToWebhooks = false;
public function webhooks(): array
{
return $this->visitsWebhooks;
}
public function hasWebhooks(): bool
{
return ! empty($this->visitsWebhooks);
}
protected function setVisitsWebhooks(array $visitsWebhooks): void
{
$this->visitsWebhooks = $visitsWebhooks;
}
public function notifyOrphanVisits(): bool
{
return $this->notifyOrphanVisitsToWebhooks;
}
protected function setNotifyOrphanVisitsToWebhooks(bool $notifyOrphanVisitsToWebhooks): void
{
$this->notifyOrphanVisitsToWebhooks = $notifyOrphanVisitsToWebhooks;
}
}