<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use App\Entity\Category;
use App\Entity\Product;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class PathExtension extends AbstractExtension
{
public function __construct(
private UrlGeneratorInterface $router,
private RequestStack $requestStack
) {}
public function getFunctions()
{
return array(
new \Twig\TwigFunction('inPath', array($this, 'inPath')),
new \Twig\TwigFunction('product_path', array($this, 'productPath')),
new \Twig\TwigFunction('product_url', array($this, 'productUrl')),
);
}
public function inPath(Category $category, $path)
{
foreach($path as $p){
if($p->getId() == $category->getId()){
return true;
}
}
return false;
}
/**
* URL unique de la fiche d'un produit : la fiche modèle (avec l'ancre de présélection)
* pour une déclinaison, la fiche produit sinon. Évite de lier des URL qui redirigent en 301.
*/
public function productPath(Product $product, bool $withAnchor = true, int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
$productModel = $product->getTopProductModel();
if($productModel) {
$request = $this->requestStack->getCurrentRequest();
$productModel->translate($request ? $request->getLocale() : 'fr');
$url = $this->router->generate('product_model', ['id'=>$productModel->getId(), 'url'=>$productModel->getUrl()], $referenceType);
return $withAnchor ? $url.'#p='.$product->getId() : $url;
}
return $this->router->generate('product', ['id'=>$product->getId(), 'url'=>$product->getUrl()], $referenceType);
}
public function productUrl(Product $product, bool $withAnchor = true): string
{
return $this->productPath($product, $withAnchor, UrlGeneratorInterface::ABSOLUTE_URL);
}
public function getName()
{
return 'path_extension';
}
}