<?php
namespace App\Website\LinkGenerator;
use Pimcore\Model\DataObject\ClassDefinition\LinkGeneratorInterface;
use Pimcore\Model\DataObject\Product;
use Pimcore\Tool;
use Pimcore\Twig\Extension\Templating\PimcoreUrl;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\String\Slugger\SluggerInterface;
class ProductLinkGenerator implements LinkGeneratorInterface {
public function __construct(
private SluggerInterface $slugger,
private PimcoreUrl $pimcoreUrl,
private ContainerInterface $container){
}
public function generate($object, $params = []): string{
if(!$object instanceof Product){
throw new \InvalidArgumentException('Object must be an instance of Product');
}
$slug = $this->slugger->slug($object->getName())->lower()->toString();
$link = $this->pimcoreUrl->__invoke([
'slug' => $slug,
'productId' => $object->getId(),
], 'product_show', true);
if(!str_contains($link, 'https://') || !str_contains($link, 'http://')){
$protocol = $this->container->getParameter('site_protocol');
$link = Tool::getHostUrl($protocol) . $link;
}
return $link;
}
}