<?php
declare(strict_types=1);
namespace BitBag\OpenMarketplace\Component\Elasticsearch\PropertyBuilder;
use BitBag\OpenMarketplace\Component\Product\Entity\ProductInterface;
use BitBag\OpenMarketplace\Component\Tag\Entity\ProductTagInterface;
use BitBag\OpenMarketplace\Component\Tag\Entity\TagTranslationInterface;
use BitBag\SyliusElasticsearchPlugin\PropertyBuilder\AbstractBuilder;
use Elastica\Document;
use FOS\ElasticaBundle\Event\PostTransformEvent;
final class TagNameBuilder extends AbstractBuilder
{
public function __construct(
private string $tagProperty,
) {
}
public function consumeEvent(PostTransformEvent $event): void
{
$this->buildProperty(
$event,
ProductInterface::class,
function (ProductInterface $product, Document $document): void {
$tags = $this->resolveTranslations($product);
foreach ($tags as $localeCode => $tagNames) {
$document->set(
sprintf('%s_%s', $this->tagProperty, $localeCode),
$tagNames
);
}
}
);
}
private function resolveTranslations(ProductInterface $product): array
{
$tags = [];
/** @var ProductTagInterface $productTag */
foreach ($product->getProductTags() as $productTag) {
$tagTranslations = $productTag->getTag()?->getTranslations() ?? [];
/** @var TagTranslationInterface $tagTranslation */
foreach ($tagTranslations as $tagTranslation) {
$locale = $tagTranslation->getLocale() ?? '';
if (!array_key_exists($locale, $tags)) {
$tags[$locale] = [$tagTranslation->getName()];
continue;
}
$tags[$locale] = array_merge($tags[$locale], [$tagTranslation->getName()]);
}
}
return $tags;
}
}