src/Twig/Extension/FlashMessageExtension.php line 27

Open in your IDE?
  1. <?php 
  2. namespace App\Twig\Extension;
  3. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  4. use Twig\Extension\AbstractExtension;
  5. use Twig\TwigFunction;
  6. class FlashMessageExtension extends AbstractExtension
  7. {
  8.     private $session;
  9.     public function __construct(SessionInterface $session)
  10.     {
  11.         $this->session $session;
  12.     }
  13.     public function getFunctions(): array
  14.     {
  15.         return [
  16.             new TwigFunction('render_flashes', [$this'renderFlashes'], ['is_safe' => ['html']]),
  17.         ];
  18.     }
  19.     public function renderFlashes(): string
  20.     {
  21.         $flashes $this->session->getFlashBag()->all();
  22.         $output '';
  23.         foreach ($flashes as $label => $messages) {
  24.             foreach ($messages as $message) {
  25.                 $output .= sprintf(
  26.                     '<div class="alert alert-%s">%s</div>',
  27.                     htmlspecialchars($labelENT_QUOTES'UTF-8'),
  28.                     htmlspecialchars($messageENT_QUOTES'UTF-8')
  29.                 );
  30.             }
  31.         }
  32.         return $output;
  33.     }
  34. }