app/Customize/EventSubscriber/LpStarterCleanupSubscriber.php line 49

Open in your IDE?
  1. <?php
  2. namespace Customize\EventSubscriber;
  3. use Eccube\Service\CartService;
  4. use Eccube\Repository\ProductClassRepository;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class LpStarterCleanupSubscriber implements EventSubscriberInterface
  9. {
  10.     // default TTL (2 hours)
  11.     private const DEFAULT_TTL 7200;
  12.     public function __construct(
  13.         private CartService $cartService,
  14.         private ProductClassRepository $productClassRepository
  15.     ) {}
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::REQUEST => ['onKernelRequest'0],
  20.         ];
  21.     }
  22. public function onKernelRequest(RequestEvent $event): void
  23. {
  24.     if (!$event->isMainRequest()) return;
  25.     $request $event->getRequest();
  26.     $session $request->getSession();
  27.     if (!$session) return;
  28.     // Allow setting ttl via query ONCE, and persist it
  29.     if ($request->query->has('lp_cleanup_ttl')) {
  30.         $ttl max(0, (int) $request->query->get('lp_cleanup_ttl'));
  31.         $session->set('lp_cleanup_ttl'$ttl);
  32.     }
  33.     // Optional: force cleanup param
  34.     if ($request->query->getBoolean('lp_force_cleanup')) {
  35.         $this->clearLpCart($session);
  36.         return;
  37.     }
  38.     // Only act for LP flow
  39.     if ($session->get('lp_flow') !== '1') return;
  40.     $addedAt = (int) $session->get('lp_starter_added_at'0);
  41.     if ($addedAt <= 0) return;
  42.     $ttl = (int) $session->get('lp_cleanup_ttl'self::DEFAULT_TTL);
  43.     if ($ttl <= 0) return;
  44.     if (time() - $addedAt $ttl) return;
  45.     $this->clearLpCart($session);
  46.     
  47. }
  48. private function clearLpCart($session): void
  49. {
  50.     if (method_exists($this->cartService'clear')) {
  51.         $this->cartService->clear();
  52.         $this->cartService->save();
  53.     }
  54.     // remove flags so we don't keep clearing forever
  55.     $session->remove('lp_flow');
  56.     $session->remove('lp_starter_added_at');
  57.     $session->remove('lp_cleanup_ttl');
  58. }
  59.     private function clearLpFlags($session): void
  60.     {
  61.         foreach ([
  62.             'lp_starter_seeded',
  63.             'lp_starter_seeded_at',
  64.             'lp_starter_pc_id',
  65.             'lp_starter_seed_reason',
  66.         ] as $k) {
  67.             $session->remove($k);
  68.         }
  69.     }
  70. }