<?php
namespace App\Twig;
use App\Entity\BienEtre\BienEtre;
use App\Entity\Contenu\ConseilJambeLegere;
use App\Entity\Contenu\Page;
use App\Entity\Produit\Produit;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class GeturlExtension extends AbstractExtension
{
private $entityManager;
private $router;
public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $router)
{
$this->entityManager = $entityManager;
$this->router = $router;
}
public function getFilters(): array
{
return [
// If your filter generates SAFE HTML, you should add a third
// parameter: ['is_safe' => ['html']]
// Reference: https://twig.symfony.com/doc/2.x/advanced.html#automatic-escaping
new TwigFilter('geturl', [$this, 'doSomething']),
];
}
public function getFunctions(): array
{
return [
new TwigFunction('geturl', [$this, 'doSomething']),
];
}
public function doSomething($value, $entity, $name = null)
{
$em = $this->entityManager;
switch ($entity) {
case 'bienetre':
$name = is_null($name) ? 'product_presentation_product_show' : $name;
$repo = $em->getRepository(BienEtre::class);
break;
case 'produit':
$name = is_null($name) ? 'produit.detail' : $name;
$repo = $em->getRepository(Produit::class);
break;
case 'conseiljambelegere':
$name = is_null($name) ? 'conseil_jambe_legere.detail' : $name;
$repo = $em->getRepository(ConseilJambeLegere::class);
break;
case 'page':
default:
$name = is_null($name) ? 'page.detail' : $name;
$repo = $em->getRepository(Page::class);
break;
}
$slug = null === $repo->find($value) ? '' : (string) $repo->find($value)->getSlug();
return $this->router->generate(
$name,
[
'slug' => $slug
]
) ?? '';
}
}