src/Twig/Extension/ProductPageExtension.php line 80

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Enterprise License (PEL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PEL
  13.  */
  14. namespace App\Twig\Extension;
  15. use App\Model\Product\Product;
  16. use App\Website\LinkGenerator\ProductLinkGenerator;
  17. use Pimcore\Bundle\EcommerceFrameworkBundle\Model\ProductInterface;
  18. use Pimcore\Translation\Translator;
  19. use Twig\Extension\AbstractExtension;
  20. use Twig\TwigFilter;
  21. use Twig\TwigFunction;
  22. class ProductPageExtension extends AbstractExtension
  23. {
  24.     /**
  25.      * @var ProductLinkGenerator
  26.      */
  27.     protected $productLinkGenerator;
  28.     /**
  29.      * @var Translator
  30.      */
  31.     protected $translator;
  32.     /**
  33.      * ProductPageExtension constructor.
  34.      *
  35.      * @param ProductLinkGenerator $productLinkGenerator
  36.      * @param Translator $translator
  37.      */
  38.     public function __construct(ProductLinkGenerator $productLinkGeneratorTranslator $translator)
  39.     {
  40.         $this->productLinkGenerator $productLinkGenerator;
  41.         $this->translator $translator;
  42.     }
  43.     /**
  44.      * @return TwigFunction[]
  45.      */
  46.     public function getFunctions()
  47.     {
  48.         return [
  49.             new TwigFunction('app_product_detaillink', [$this'generateLink']),
  50.         ];
  51.     }
  52.     /**
  53.      * @return TwigFilter[]
  54.      */
  55.     public function getFilters()
  56.     {
  57.         return [
  58.             new TwigFilter('colorname', [$this'getColorName'])
  59.         ];
  60.     }
  61.     /**
  62.      * @param array|Product $product
  63.      *
  64.      * @return string
  65.      */
  66.     public function generateLink(array|Product $product): string
  67.     {
  68.         if(!$product instanceof Product)
  69.             $product Product::getById($product['id']);
  70.         return $this->productLinkGenerator->generate($product, []);
  71.     }
  72.     /**
  73.      * @param array|null $colorNames
  74.      *
  75.      * @return string
  76.      */
  77.     public function getColorName(?array $colorNames = []): string
  78.     {
  79.         $translatedColors = [];
  80.         if ($colorNames) {
  81.             foreach ($colorNames as $color) {
  82.                 $translatedColors[] = $this->translator->trans($color);
  83.             }
  84.         }
  85.         return implode('-'$translatedColors);
  86.     }
  87. }