<?php
declare(strict_types=1);
namespace BitBag\OpenMarketplace\Component\Elasticsearch\PropertyBuilder;
use BitBag\OpenMarketplace\Component\Product\Entity\ProductCountryAdjustmentInterface;
use BitBag\OpenMarketplace\Component\Product\Entity\ProductInterface;
use BitBag\SyliusElasticsearchPlugin\PropertyBuilder\AbstractBuilder;
use Elastica\Document;
use FOS\ElasticaBundle\Event\PostTransformEvent;
use Sylius\Component\Locale\Provider\LocaleProviderInterface;
final class CountriesPropertyBuilder extends AbstractBuilder
{
public function __construct(
private LocaleProviderInterface $localeProvider,
private string $countriesProperty,
private string $countryNamesProperty,
) {
}
public function consumeEvent(PostTransformEvent $event): void
{
$this->buildProperty(
$event,
ProductInterface::class,
function (ProductInterface $product, Document $document): void {
$countries = [];
/** @var ProductCountryAdjustmentInterface $adjustment */
foreach ($product->getCountryAdjustments() as $adjustment) {
if (true === $adjustment->isEnabled()) {
$countries[] = $adjustment->getCountry()?->getCode();
}
}
$document->set($this->countriesProperty, $countries);
$locales = $this->localeProvider->getAvailableLocalesCodes();
foreach ($locales as $localeCode) {
$document->set(
$this->resolvePropertyName($localeCode),
$this->resolveCountryNames($product, $localeCode),
);
}
}
);
}
private function resolvePropertyName(string $localeCode): string
{
return sprintf('%s_%s', $this->countryNamesProperty, $localeCode);
}
private function resolveCountryNames(ProductInterface $product, string $localeCode): array
{
$countryNames = [];
/** @var ProductCountryAdjustmentInterface $adjustment */
foreach ($product->getCountryAdjustments() as $adjustment) {
if (true === $adjustment->isEnabled()) {
$countryNames[] = $adjustment->getCountry()?->getName($localeCode);
}
}
return $countryNames;
}
}