<?php
/*
* Copyright(c) 2019 SYSTEM FRIEND INC.
*/
namespace Plugin\CheckProduct42\EventSubscriber;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Plugin\CheckProduct42\Service\CookieHelper;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CheckProductEvent implements EventSubscriberInterface
{
protected \Plugin\CheckProduct42\Common\EccubeConfigEx $checkProductConfig;
protected CookieHelper $cookieHelper;
protected $cookie;
/**
* CheckProductEvent constructor.
*
* @param \Plugin\CheckProduct42\Common\EccubeConfigEx $checkProductConfig
* @param CookieHelper $cookieHelper
*/
public function __construct(
\Plugin\CheckProduct42\Common\EccubeConfigEx $checkProductConfig,
CookieHelper $cookieHelper
)
{
$this->checkProductConfig = $checkProductConfig;
$this->cookieHelper = $cookieHelper;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE => 'createCookie',
];
}
/**
* クッキーに商品IDを保存
*
* @param ResponseEvent $event
* @throws \Exception
*/
public function onKernelResponse(ResponseEvent $event)
{
$request = $event->getRequest();
if ($request->get('_route') !== 'product_detail') {
return;
}
if($this->cookie){
$response = $this->cookieHelper->setCookie($event->getResponse(), $this->cookie);
// Cookieをレスポンスにセット
$event->setResponse($response);
}
}
/**
* クッキーを作成
* 形式: "商品ID:タイムスタンプ,商品ID:タイムスタンプ,..."
*
* @param EventArgs $event
* @throws \Exception
*/
public function createCookie(EventArgs $event)
{
$Product = $event->getArgument('Product');
$productId = $Product->getId();
$now = time();
// 既存のデータを取得(商品ID => タイムスタンプ)
$productData = $this->cookieHelper->getProductData();
// 現在の商品のタイムスタンプを更新(または新規追加)
$productData[$productId] = $now;
// タイムスタンプの降順(新しい順)でソート
arsort($productData);
// Cookie保存数は100件に制限(パレス/プラザどちらにログインするか分からないため多めに保存)
$productData = array_slice($productData, 0, 100, true);
// "商品ID:タイムスタンプ" 形式の配列を作成
$cookieItems = [];
foreach ($productData as $id => $timestamp) {
$cookieItems[] = $id . ':' . $timestamp;
}
// 保持期間1ヶ月
$expire = new \DateTime();
$month = 1;
$expire->modify("$month month");
// Cookie作成
$cookie = new Cookie(
$this->cookieHelper->getCookieName(),
implode(',', $cookieItems),
$expire,
$this->checkProductConfig->get('env(ECCUBE_COOKIE_PATH)')
);
$this->cookie = $cookie;
}
}