src/Component/Elasticsearch/PropertyBuilder/TagNameBuilder.php line 21

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace BitBag\OpenMarketplace\Component\Elasticsearch\PropertyBuilder;
  4. use BitBag\OpenMarketplace\Component\Product\Entity\ProductInterface;
  5. use BitBag\OpenMarketplace\Component\Tag\Entity\ProductTagInterface;
  6. use BitBag\OpenMarketplace\Component\Tag\Entity\TagTranslationInterface;
  7. use BitBag\SyliusElasticsearchPlugin\PropertyBuilder\AbstractBuilder;
  8. use Elastica\Document;
  9. use FOS\ElasticaBundle\Event\PostTransformEvent;
  10. final class TagNameBuilder extends AbstractBuilder
  11. {
  12.     public function __construct(
  13.         private string $tagProperty,
  14.     ) {
  15.     }
  16.     public function consumeEvent(PostTransformEvent $event): void
  17.     {
  18.         $this->buildProperty(
  19.             $event,
  20.             ProductInterface::class,
  21.             function (ProductInterface $productDocument $document): void {
  22.                 $tags $this->resolveTranslations($product);
  23.                 foreach ($tags as $localeCode => $tagNames) {
  24.                     $document->set(
  25.                         sprintf('%s_%s'$this->tagProperty$localeCode),
  26.                         $tagNames
  27.                     );
  28.                 }
  29.             }
  30.         );
  31.     }
  32.     private function resolveTranslations(ProductInterface $product): array
  33.     {
  34.         $tags = [];
  35.         /** @var ProductTagInterface $productTag */
  36.         foreach ($product->getProductTags() as $productTag) {
  37.             $tagTranslations $productTag->getTag()?->getTranslations() ?? [];
  38.             /** @var TagTranslationInterface $tagTranslation */
  39.             foreach ($tagTranslations as $tagTranslation) {
  40.                 $locale $tagTranslation->getLocale() ?? '';
  41.                 if (!array_key_exists($locale$tags)) {
  42.                     $tags[$locale] = [$tagTranslation->getName()];
  43.                     continue;
  44.                 }
  45.                 $tags[$locale] = array_merge($tags[$locale], [$tagTranslation->getName()]);
  46.             }
  47.         }
  48.         return $tags;
  49.     }
  50. }