<?php
namespace App\EventListener;
use App\Auctioneer\BiddingResult;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Twig\Environment;
class AjaxFlashListener
{
protected $session;
public function __construct(SessionInterface $session, private readonly Environment $templating)
{
$this->session = $session;
}
public function onKernelResponse(ResponseEvent $event): void
{
$response = $event->getResponse();
$request = $event->getRequest();
if (
$response instanceof JsonResponse
&& in_array($request->get('_route'), ['frontend_auction_bid', 'frontend_purchase_instruction_set'])
) {
$flashMessages = $this->session->getFlashBag()->all();
if (!empty($flashMessages)) {
$data = json_decode($response->getContent(), true);
foreach ($flashMessages as $status => $flashes) {
foreach ($flashes as $flash) {
if (BiddingResult::AMOUNT_BEATEN !== array_search($flash, BiddingResult::$messages)) {
$data['flash'][] = $this->templating->render('flash/_flash_notification.html.twig', [
'type' => $status,
'message' => $flash,
'duration' => 'short',
]);
}
}
}
$response->setData($data);
}
}
}
}