src/Twig/GeturlExtension.php line 74

Open in your IDE?
  1. <?php
  2. namespace App\Twig;
  3. use App\Entity\BienEtre\BienEtre;
  4. use App\Entity\Contenu\ConseilJambeLegere;
  5. use App\Entity\Contenu\Page;
  6. use App\Entity\Produit\Produit;
  7. use Twig\Extension\AbstractExtension;
  8. use Twig\TwigFilter;
  9. use Twig\TwigFunction;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. class GeturlExtension extends AbstractExtension
  13. {
  14.     private $entityManager;
  15.     private $router;
  16.     public function __construct(EntityManagerInterface $entityManagerUrlGeneratorInterface $router)
  17.     {
  18.         $this->entityManager $entityManager;
  19.         $this->router $router;
  20.     }
  21.     public function getFilters(): array
  22.     {
  23.         return [
  24.             // If your filter generates SAFE HTML, you should add a third
  25.             // parameter: ['is_safe' => ['html']]
  26.             // Reference: https://twig.symfony.com/doc/2.x/advanced.html#automatic-escaping
  27.             new TwigFilter('geturl', [$this'doSomething']),
  28.         ];
  29.     }
  30.     public function getFunctions(): array
  31.     {
  32.         return [
  33.             new TwigFunction('geturl', [$this'doSomething']),
  34.         ];
  35.     }
  36.     public function doSomething($value$entity$name null)
  37.     {
  38.         $em $this->entityManager;
  39.         switch ($entity) {
  40.             case 'bienetre':
  41.                 $name is_null($name) ? 'product_presentation_product_show' :  $name;
  42.                 $repo $em->getRepository(BienEtre::class);
  43.                 break;
  44.             case 'produit':
  45.                 $name is_null($name) ? 'produit.detail' $name;
  46.                 $repo $em->getRepository(Produit::class);
  47.                 break;
  48.             case 'conseiljambelegere':
  49.                 $name is_null($name) ? 'conseil_jambe_legere.detail' $name;
  50.                 $repo $em->getRepository(ConseilJambeLegere::class);
  51.                 break;
  52.             case 'page':
  53.             default:
  54.                 $name is_null($name) ?  'page.detail' $name;
  55.                 $repo $em->getRepository(Page::class);
  56.                 break;
  57.         }
  58.         $slug null === $repo->find($value) ? '' : (string) $repo->find($value)->getSlug();
  59.         return $this->router->generate(
  60.             $name,
  61.             [
  62.                 'slug' => $slug
  63.             ]
  64.         ) ?? '';
  65.     }
  66. }