vendor/bitbag/elasticsearch-plugin/src/PropertyBuilder/ProductTaxonsBuilder.php line 32
<?php
/*
* This file has been created by developers from BitBag.
* Feel free to contact us once you face any issues or want to start
* another great project.
* You can find more information about us on https://bitbag.io and write us
* an email on hello@bitbag.io.
*/
declare(strict_types=1);
namespace BitBag\SyliusElasticsearchPlugin\PropertyBuilder;
use BitBag\SyliusElasticsearchPlugin\PropertyBuilder\Mapper\ProductTaxonsMapperInterface;
use Elastica\Document;
use FOS\ElasticaBundle\Event\PostTransformEvent;
use Sylius\Component\Core\Model\ProductInterface;
final class ProductTaxonsBuilder extends AbstractBuilder
{
private ProductTaxonsMapperInterface $productTaxonsMapper;
private string $taxonsProperty;
public function __construct(ProductTaxonsMapperInterface $productTaxonsMapper, string $taxonsProperty)
{
$this->productTaxonsMapper = $productTaxonsMapper;
$this->taxonsProperty = $taxonsProperty;
}
public function consumeEvent(PostTransformEvent $event): void
{
$this->buildProperty(
$event,
ProductInterface::class,
function (ProductInterface $product, Document $document): void {
$taxons = $this->productTaxonsMapper->mapToUniqueCodesLang($product);
$uniqueObjects = [];
foreach ($taxons as $object) {
// Convert the object to a string to use it as a unique key
$objectKey = json_encode($object, JSON_UNESCAPED_UNICODE);
// Add the object to the uniqueObjects array if not already encountered
if (!isset($uniqueObjects[$objectKey])) {
$uniqueObjects[$objectKey] = $object;
}
}
// Convert the associative array back to indexed array
$uniqueArray = array_values($uniqueObjects);
$document->set($this->taxonsProperty, $uniqueArray);
}
);
}
}