<?php
namespace App\EventListener\Strava;
use App\Entity\SocialToken;
use App\Entity\User;
use App\Repository\SocialTokenRepository;
use Doctrine\ORM\EntityManagerInterface;
use NuBox\Strava\Api\Event\StravaApiEvents;
use NuBox\Strava\Api\Event\Webhook\ActivityDeletedEvent;
use NuBox\Strava\Api\Event\Webhook\WebhookEventInterface;
use NuBox\Strava\Api\Service\StravaApi;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class WebhookAthleteSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly SocialTokenRepository $socialTokenRepository,
private readonly EntityManagerInterface $entityManager,
) {
}
public static function getSubscribedEvents(): array
{
return [
StravaApiEvents::WEBHOOK_ATHLETE_DELETED => 'onAthleteDeleted',
];
}
public function onAthleteDeleted(ActivityDeletedEvent $event): void
{
$socialToken = $this->getSocialToken($event);
$this->entityManager->remove($socialToken);
$this->entityManager->flush();
}
private function getSocialToken(WebhookEventInterface $event): SocialToken
{
$socialUserId = $event->getWebhook()->getOwnerId();
$socialToken = $this->socialTokenRepository->findOneBy([
'type' => StravaApi::TYPE,
'socialUserId' => $socialUserId,
]);
assert($socialToken instanceof SocialToken);
return $socialToken;
}
}