Passed
Push — master ( 59f96f...9edaa9 )
by Mikołaj
05:36
created

AttributeBuilder::buildProperty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag. 
5
 * Feel free to contact us once you face any issues or want to start
6
 * another great project. 
7
 * You can find more information about us on https://bitbag.shop and write us
8
 * an email on [email protected]. 
9
 */
10
11
declare(strict_types=1);
12
13
namespace BitBag\SyliusElasticsearchPlugin\PropertyBuilder;
14
15
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\ConcatedNameResolverInterface;
16
use Elastica\Document;
17
use FOS\ElasticaBundle\Event\TransformEvent;
18
use Sylius\Component\Core\Model\ProductInterface;
19
20
final class AttributeBuilder extends AbstractBuilder
21
{
22
    /**
23
     * @var ConcatedNameResolverInterface
24
     */
25
    private $attributeNameResolver;
26
27
    /**
28
     * @param ConcatedNameResolverInterface $attributeNameResolver
29
     */
30
    public function __construct(ConcatedNameResolverInterface $attributeNameResolver)
31
    {
32
        $this->attributeNameResolver = $attributeNameResolver;
33
    }
34
35
    /**
36
     * @param TransformEvent $event
37
     */
38
    public function buildProperty(TransformEvent $event): void
39
    {
40
        /** @var ProductInterface $product */
41
        $product = $event->getObject();
42
43
        if (!$product instanceof ProductInterface) {
0 ignored issues
show
introduced by
$product is always a sub-type of Sylius\Component\Core\Model\ProductInterface.
Loading history...
44
            return;
45
        }
46
47
        $document = $event->getDocument();
48
49
        $this->resolveProductAttributes($product, $document);
50
    }
51
52
    /**
53
     * @param ProductInterface $product
54
     * @param Document $document
55
     */
56
    private function resolveProductAttributes(ProductInterface $product, Document $document): void
57
    {
58
        foreach ($product->getAttributes() as $attributeValue) {
59
            $attributeCode = $attributeValue->getAttribute()->getCode();
60
            $index = $this->attributeNameResolver->resolvePropertyName($attributeCode);
61
62
            if (!$document->has($index)) {
63
                $document->set($index, []);
64
            }
65
66
            $reference = $document->get($index);
67
            $reference[] = $attributeValue->getValue();
68
69
            $document->set($index, $reference);
70
        }
71
    }
72
}
73