AttributeTaxonsBuilder::consumeEvent()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 1
dl 0
loc 20
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file was created by developers working at BitBag
5
 * Do you need more information about us and what we do? Visit our https://bitbag.io website!
6
 * We are hiring developers from all over the world. Join us and start your new, exciting adventure and become part of us: https://bitbag.io/career
7
*/
8
9
declare(strict_types=1);
10
11
namespace BitBag\SyliusElasticsearchPlugin\PropertyBuilder;
12
13
use BitBag\SyliusElasticsearchPlugin\Repository\TaxonRepositoryInterface;
14
use FOS\ElasticaBundle\Event\PostTransformEvent;
15
use Sylius\Component\Attribute\Model\AttributeInterface;
16
17
final class AttributeTaxonsBuilder extends AbstractBuilder
18
{
19
    /** @var TaxonRepositoryInterface */
20
    protected $taxonRepository;
21
22
    /** @var string */
23
    private $taxonsProperty;
24
25
    /** @var array */
26
    private $excludedAttributes;
27
28
    public function __construct(
29
        TaxonRepositoryInterface $taxonRepository,
30
        string $taxonsProperty,
31
        array $excludedAttributes = []
32
    ) {
33
        $this->taxonRepository = $taxonRepository;
34
        $this->taxonsProperty = $taxonsProperty;
35
        $this->excludedAttributes = $excludedAttributes;
36
    }
37
38
    public function consumeEvent(PostTransformEvent $event): void
39
    {
40
        $documentAttribute = $event->getObject();
41
42
        if (!$documentAttribute instanceof AttributeInterface
43
            || in_array($documentAttribute->getCode(), $this->excludedAttributes)
44
        ) {
45
            return;
46
        }
47
48
        $taxons = $this->taxonRepository->getTaxonsByAttributeViaProduct($documentAttribute);
49
        $taxonCodes = [];
50
51
        foreach ($taxons as $taxon) {
52
            $taxonCodes[] = $taxon->getCode();
53
        }
54
55
        $document = $event->getDocument();
56
57
        $document->set($this->taxonsProperty, $taxonCodes);
58
    }
59
}
60