vendor/bitbag/elasticsearch-plugin/src/PropertyBuilder/AttributeTaxonsBuilder.php line 43

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file has been created by developers from BitBag.
  4.  * Feel free to contact us once you face any issues or want to start
  5.  * another great project.
  6.  * You can find more information about us on https://bitbag.io and write us
  7.  * an email on hello@bitbag.io.
  8.  */
  9. declare(strict_types=1);
  10. namespace BitBag\SyliusElasticsearchPlugin\PropertyBuilder;
  11. use BitBag\SyliusElasticsearchPlugin\Repository\TaxonRepositoryInterface;
  12. use FOS\ElasticaBundle\Event\PostTransformEvent;
  13. use Sylius\Component\Attribute\Model\AttributeInterface;
  14. use Sylius\Component\Core\Model\TaxonInterface;
  15. use Sylius\Component\Product\Model\ProductAttributeInterface;
  16. final class AttributeTaxonsBuilder extends AbstractBuilder
  17. {
  18.     protected TaxonRepositoryInterface $taxonRepository;
  19.     private string $taxonsProperty;
  20.     private array $excludedAttributes;
  21.     private bool $includeAllDescendants;
  22.     public function __construct(
  23.         TaxonRepositoryInterface $taxonRepository,
  24.         string $taxonsProperty,
  25.         bool $includeAllDescendants,
  26.         array $excludedAttributes = []
  27.     ) {
  28.         $this->taxonRepository $taxonRepository;
  29.         $this->taxonsProperty $taxonsProperty;
  30.         $this->includeAllDescendants $includeAllDescendants;
  31.         $this->excludedAttributes $excludedAttributes;
  32.     }
  33.     public function consumeEvent(PostTransformEvent $event): void
  34.     {
  35.         $documentAttribute $event->getObject();
  36.         if (!$documentAttribute instanceof AttributeInterface
  37.             || !$documentAttribute instanceof ProductAttributeInterface
  38.             || in_array($documentAttribute->getCode(), $this->excludedAttributes)
  39.         ) {
  40.             return;
  41.         }
  42.         $taxons $this->taxonRepository->getTaxonsByAttributeViaProduct($documentAttribute);
  43.         $taxonCodes = [];
  44.         /** @var TaxonInterface $taxon */
  45.         foreach ($taxons as $taxon) {
  46.             $taxonCodes[] = $taxon->getCode();
  47.             if (true === $this->includeAllDescendants) {
  48.                 foreach ($taxon->getAncestors() as $ancestor) {
  49.                     $taxonCodes[] = $ancestor->getCode();
  50.                 }
  51.             }
  52.         }
  53.         $document $event->getDocument();
  54.         $document->set($this->taxonsProperty$taxonCodes);
  55.     }
  56. }