src/Twig/PathExtension.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Twig;
  3. use Twig\Extension\AbstractExtension;
  4. use Twig\TwigFunction;
  5. use App\Entity\Category;
  6. use App\Entity\Product;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. class PathExtension extends AbstractExtension
  10. {
  11. public function __construct(
  12. private UrlGeneratorInterface $router,
  13. private RequestStack $requestStack
  14. ) {}
  15. public function getFunctions()
  16. {
  17. return array(
  18. new \Twig\TwigFunction('inPath', array($this, 'inPath')),
  19. new \Twig\TwigFunction('product_path', array($this, 'productPath')),
  20. new \Twig\TwigFunction('product_url', array($this, 'productUrl')),
  21. );
  22. }
  23. public function inPath(Category $category, $path)
  24. {
  25. foreach($path as $p){
  26. if($p->getId() == $category->getId()){
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32. /**
  33. * URL unique de la fiche d'un produit : la fiche modèle (avec l'ancre de présélection)
  34. * pour une déclinaison, la fiche produit sinon. Évite de lier des URL qui redirigent en 301.
  35. */
  36. public function productPath(Product $product, bool $withAnchor = true, int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
  37. {
  38. $productModel = $product->getTopProductModel();
  39. if($productModel) {
  40. $request = $this->requestStack->getCurrentRequest();
  41. $productModel->translate($request ? $request->getLocale() : 'fr');
  42. $url = $this->router->generate('product_model', ['id'=>$productModel->getId(), 'url'=>$productModel->getUrl()], $referenceType);
  43. return $withAnchor ? $url.'#p='.$product->getId() : $url;
  44. }
  45. return $this->router->generate('product', ['id'=>$product->getId(), 'url'=>$product->getUrl()], $referenceType);
  46. }
  47. public function productUrl(Product $product, bool $withAnchor = true): string
  48. {
  49. return $this->productPath($product, $withAnchor, UrlGeneratorInterface::ABSOLUTE_URL);
  50. }
  51. public function getName()
  52. {
  53. return 'path_extension';
  54. }
  55. }