app/Customize/EventListener/IntroductionCodeListener.php line 43

Open in your IDE?
  1. <?php
  2. namespace Customize\EventListener;
  3. use Eccube\Common\EccubeConfig;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  6. use Symfony\Component\HttpKernel\{
  7.     Event\RequestEvent,
  8.     KernelEvents
  9. };
  10. class IntroductionCodeListener implements EventSubscriberInterface
  11. {
  12.     /** @var SessionInterface */
  13.     private $session;
  14.     /** @var EccubeConfig */
  15.     private $eccubeConfig;
  16.     public function __construct(SessionInterface $sessionEccubeConfig $eccubeConfig)
  17.     {
  18.         $this->session $session;
  19.         $this->eccubeConfig $eccubeConfig;
  20.     }
  21.     public static function getSubscribedEvents()
  22.     {
  23.         // NOTE: 数字が大きいほど早く実行される。16は、Symfonyのコアコンポーネントやその他のミドルウェアの実行より前に
  24.         // しかし、最重要な初期化処理の後に実行されるように設定
  25.         return [
  26.             KernelEvents::REQUEST => ['onKernelRequest'16],
  27.         ];
  28.     }
  29.     /**
  30.      * 紹介コードのリクエストを処理
  31.      *
  32.      * @param RequestEvent $event
  33.      * @return void
  34.      */
  35.     public function onKernelRequest(RequestEvent $event): void
  36.     {
  37.         $request $event->getRequest();
  38.         // 商品詳細ページへのリクエストかチェック
  39.         if (!preg_match('#^/products/detail/\d+#'$request->getPathInfo())) {
  40.             return;
  41.         }
  42.         // リファラルコードのパラメータを取得
  43.         $introductionCode $request->query->get('introduction_code');
  44.         if ($introductionCode) {
  45.             // 紹介コードのバリデーション
  46.             $validLength $this->eccubeConfig->get('kofun_introduction_code_len');
  47.             if (!preg_match('/^\d{'.$validLength.'}$/'$introductionCode)) {
  48.                 return; // 不正な形式の場合は保存しない
  49.             }
  50.             $productId $this->extractProductId($request->getPathInfo());
  51.             if ($productId) {
  52.                 // 既存の紹介コード情報を取得
  53.                 $productIntroductionCodes $this->session->get('product_introduction_codes', []);
  54.                 // 商品IDをキーとして紹介コードを保存
  55.                 $productIntroductionCodes[$productId] = $introductionCode;
  56.                 // セッションに保存
  57.                 $this->session->set('product_introduction_codes'$productIntroductionCodes);
  58.             }
  59.         }
  60.     }
  61.     /**
  62.      * URLから商品IDを抽出
  63.      */
  64.     private function extractProductId(string $pathInfo): ?int
  65.     {
  66.         if (preg_match('#/products/detail/(\d+)#'$pathInfo$matches)) {
  67.             return (int) $matches[1];
  68.         }
  69.         return null;
  70.     }
  71. }