<?php
declare(strict_types=1);
namespace App\Module\Checkout\Subscriber;
use App\Module\Checkout\Normalizer\CartNormalizer;
use App\Module\ShortSimpleCheckout\Event\View\CartDispatchEvent;
use App\Module\ShortSimpleCheckout\Events;
use App\Module\ShortSimpleCheckout\Exception\VariableAlreadyDefinedException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
* Render the cart for ajax requests
*
* @author André Varelmann <andre.varelmann@bestit-online.de>
* @package App\Module\Checkout\Subscriber
*/
class RenderAjaxCartSubscriber implements EventSubscriberInterface
{
private CartNormalizer $cartNormalizer;
private Environment $twig;
/**
* RenderAjaxCartSubscriber constructor.
*
* @param CartNormalizer $cartNormalizer
* @param Environment $twig
*/
public function __construct(CartNormalizer $cartNormalizer, Environment $twig)
{
$this->cartNormalizer = $cartNormalizer;
$this->twig = $twig;
}
/**
* Get subscribed events
*
* @return array|string[]
*/
public static function getSubscribedEvents(): array
{
return [Events::CART_INDEX_AJAX_DISPATCH => 'render'];
}
/**
* Render cart in twig and return "html" property and line items count in json result
*
* @param CartDispatchEvent $event
*
* @throws LoaderError Twig error
* @throws RuntimeError Twig error
* @throws SyntaxError Twig error
* @throws VariableAlreadyDefinedException When variable already defined
*
* @return void
*/
public function render(CartDispatchEvent $event): void
{
$event->addVariable(
'html',
$this->twig->render('components/organisms/offcanvas-cart-line-item/offcanvas-cart-line-item.html.twig')
);
}
}