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.         // Don't throttle local IPs
  24.         if (!filter_var($event->getRequest()->getClientIp(), FILTER_VALIDATE_IPFILTER_FLAG_NO_PRIV_RANGE FILTER_FLAG_NO_RES_RANGE)) {
  25.             return;
  26.         }
  27.         $throttleLeadsGeneratedLimit 5;
  28.         if ($this->entityManager->getFilters()->isEnabled('softdeleteable')) {
  29.             $this->entityManager->getFilters()->disable('softdeleteable');
  30.         }
  31.         $date = new \DateTime();
  32.         $leadCountByIp $this->leadRepository->countSpamLeadByIp(
  33.             $event->getRequest()->getClientIp(),
  34.             $date->sub(new \DateInterval('PT6H'))
  35.         );
  36.         $this->entityManager->getFilters()->enable('softdeleteable');
  37.         if ($leadCountByIp >= $throttleLeadsGeneratedLimit) {
  38.             $sleepRatio $throttleLeadsGeneratedLimit max($leadCountByIp1);
  39.             $sleepTime round($leadCountByIp $sleepRatio0);
  40.             sleep(min($sleepTime55));
  41.             $event->setResponse(new Response('Unprocessable Entity'Response::HTTP_TOO_MANY_REQUESTS));
  42.         }
  43.     }
  44.     public static function getSubscribedEvents(): array
  45.     {
  46.         return [
  47.             KernelEvents::REQUEST => 'onKernelRequest',
  48.         ];
  49.     }
  50. }