src/Component/Elasticsearch/PropertyBuilder/CountriesPropertyBuilder.php line 23

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\ProductCountryAdjustmentInterface;
  5. use BitBag\OpenMarketplace\Component\Product\Entity\ProductInterface;
  6. use BitBag\SyliusElasticsearchPlugin\PropertyBuilder\AbstractBuilder;
  7. use Elastica\Document;
  8. use FOS\ElasticaBundle\Event\PostTransformEvent;
  9. use Sylius\Component\Locale\Provider\LocaleProviderInterface;
  10. final class CountriesPropertyBuilder extends AbstractBuilder
  11. {
  12.     public function __construct(
  13.         private LocaleProviderInterface $localeProvider,
  14.         private string $countriesProperty,
  15.         private string $countryNamesProperty,
  16.         ) {
  17.     }
  18.     public function consumeEvent(PostTransformEvent $event): void
  19.     {
  20.         $this->buildProperty(
  21.             $event,
  22.             ProductInterface::class,
  23.             function (ProductInterface $productDocument $document): void {
  24.                 $countries = [];
  25.                 /** @var ProductCountryAdjustmentInterface $adjustment */
  26.                 foreach ($product->getCountryAdjustments() as $adjustment) {
  27.                     if (true === $adjustment->isEnabled()) {
  28.                         $countries[] = $adjustment->getCountry()?->getCode();
  29.                     }
  30.                 }
  31.                 $document->set($this->countriesProperty$countries);
  32.                 $locales $this->localeProvider->getAvailableLocalesCodes();
  33.                 foreach ($locales as $localeCode) {
  34.                     $document->set(
  35.                         $this->resolvePropertyName($localeCode),
  36.                         $this->resolveCountryNames($product$localeCode),
  37.                     );
  38.                 }
  39.             }
  40.         );
  41.     }
  42.     private function resolvePropertyName(string $localeCode): string
  43.     {
  44.         return sprintf('%s_%s'$this->countryNamesProperty$localeCode);
  45.     }
  46.     private function resolveCountryNames(ProductInterface $productstring $localeCode): array
  47.     {
  48.         $countryNames = [];
  49.         /** @var ProductCountryAdjustmentInterface $adjustment */
  50.         foreach ($product->getCountryAdjustments() as $adjustment) {
  51.             if (true === $adjustment->isEnabled()) {
  52.                 $countryNames[] = $adjustment->getCountry()?->getName($localeCode);
  53.             }
  54.         }
  55.         return $countryNames;
  56.     }
  57. }