<?php
namespace Customize\EventListener;
use Eccube\Entity\Order;
use Eccube\Event\TemplateEvent;
use Lm\Entity\Jancode;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class GoogleTrustedStoreEventListener implements EventSubscriberInterface
{
/**
* @var Environment
*/
private $twig;
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
'Shopping/complete.twig' => 'onShoppingComplete',
];
}
public function onKernelResponse(ResponseEvent $event)
{
//
$response = $event->getResponse();
$request = $event->getRequest();
//
if (!$event->isMasterRequest()) {
//
return;
}
//
if ($request->isXmlHttpRequest()) {
return;
}
//
$this->injectBadge($response);
}
public function onShoppingComplete(TemplateEvent $event)
{
//
$this->injectOptIn($event);
}
protected function injectBadge(Response $response)
{
//
$content = $response->getContent();
$pos = strripos($content, '</body>');
//
if (false !== $pos) {
$badge = "\n".$this->twig->render('GoogleTrustedStore/badge.twig', [
]);
$content = substr($content, 0, $pos).$badge.substr($content, $pos);
$response->setContent($content);
}
}
protected function injectOptIn(TemplateEvent $event)
{
//
$parameter = $event->hasParameter('GoogleTrustedStore') ? $event->getParameter('GoogleTrustedStore') : [];
/**
* @var Order $order
*/
if ($event->hasParameter('Order') && ($order = $event->getParameter('Order'))) {
//
$products = [];
//
foreach ($order->getProductOrderItems() as $orderItem) {
//
if (($jan = new Jancode($orderItem->getProductClass()->getId())) && ($janCode = $jan->getJanJancode())) {
//
$products[] = [
'gtin' => $janCode,
];
}
}
//
$parameter['optin']['products'] = $products;
}
//
$event->setParameter('GoogleTrustedStore', $parameter);
$event->addSnippet('GoogleTrustedStore/optin.twig');
}
}