<?php
namespace App\Twig\Extension;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class FlashMessageExtension extends AbstractExtension
{
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
public function getFunctions(): array
{
return [
new TwigFunction('render_flashes', [$this, 'renderFlashes'], ['is_safe' => ['html']]),
];
}
public function renderFlashes(): string
{
$flashes = $this->session->getFlashBag()->all();
$output = '';
foreach ($flashes as $label => $messages) {
foreach ($messages as $message) {
$output .= sprintf(
'<div class="alert alert-%s">%s</div>',
htmlspecialchars($label, ENT_QUOTES, 'UTF-8'),
htmlspecialchars($message, ENT_QUOTES, 'UTF-8')
);
}
}
return $output;
}
}