src/App/EventSubscriber/ScraperThrottleSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\Lead\LeadRepository;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class ScraperThrottleSubscriber implements EventSubscriberInterface
  10. {
  11.     private LeadRepository $leadRepository;
  12.     private EntityManagerInterface $entityManager;
  13.     public function __construct(EntityManagerInterface $entityManagerLeadRepository $leadRepository)
  14.     {
  15.         $this->entityManager $entityManager;
  16.         $this->leadRepository $leadRepository;
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         if (!$event->isMainRequest()) {
  21.             return;
  22.         }
  23.         $throttleLeadsGeneratedLimit 15;
  24.         if ($this->entityManager->getFilters()->isEnabled('softdeleteable')) {
  25.             $this->entityManager->getFilters()->disable('softdeleteable');
  26.         }
  27.         $date = new \DateTime();
  28.         $leadCountByIp $this->leadRepository->getSimilarLeadCount(
  29.             $date->sub(new \DateInterval('PT15M')),
  30.             $event->getRequest()->getClientIp()
  31.         );
  32.         $this->entityManager->getFilters()->enable('softdeleteable');
  33.         if ($leadCountByIp >= $throttleLeadsGeneratedLimit) {
  34.             $sleepRatio $throttleLeadsGeneratedLimit max($leadCountByIp1);
  35.             $sleepTime round($leadCountByIp $sleepRatio0);
  36.             sleep(min($sleepTime55));
  37.             $event->setResponse(new Response('Unprocessable Entity'Response::HTTP_TOO_MANY_REQUESTS));
  38.         }
  39.     }
  40.     public static function getSubscribedEvents(): array
  41.     {
  42.         return [
  43.             KernelEvents::REQUEST => 'onKernelRequest',
  44.         ];
  45.     }
  46. }