Passed
Push — master ( 0a90fd...0ad767 )
by Mikołaj
04:29
created

AttributePropertyBuilder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 50
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A buildProperty() 0 12 2
A resolveProductAttributes() 0 14 3
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 Elastica\Document;
16
use FOS\ElasticaBundle\Event\TransformEvent;
17
use Sylius\Component\Core\Model\ProductInterface;
18
19
final class AttributePropertyBuilder extends AbstractPropertyBuilder
20
{
21
    /**
22
     * @var string
23
     */
24
    private $attributePropertyPrefix;
25
26
    /**
27
     * @param string $attributePropertyPrefix
28
     */
29
    public function __construct(string $attributePropertyPrefix)
30
    {
31
        $this->attributePropertyPrefix = $attributePropertyPrefix;
32
    }
33
34
    /**
35
     * @param TransformEvent $event
36
     */
37
    public function buildProperty(TransformEvent $event): void
38
    {
39
        /** @var ProductInterface $product */
40
        $product = $event->getObject();
41
42
        if (!$product instanceof ProductInterface) {
0 ignored issues
show
introduced by
$product is always a sub-type of Sylius\Component\Core\Model\ProductInterface.
Loading history...
43
            return;
44
        }
45
46
        $document = $event->getDocument();
47
48
        $this->resolveProductAttributes($product, $document);
49
    }
50
51
    /**
52
     * @param ProductInterface $product
53
     * @param Document $document
54
     */
55
    private function resolveProductAttributes(ProductInterface $product, Document $document): void
56
    {
57
        foreach ($product->getAttributes() as $attributeValue) {
58
            $attributeCode = $attributeValue->getAttribute()->getCode();
59
            $index = $this->attributePropertyPrefix . '_' . $attributeCode;
60
61
            if (!$document->has($index)) {
62
                $document->set($index, []);
63
            }
64
65
            $reference = $document->get($index);
66
            $reference[] = $attributeValue->getValue();
67
68
            $document->set($index, $reference);
69
        }
70
    }
71
}
72