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

OptionPropertyBuilder   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 54
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
B resolveProductOptions() 0 18 5
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 OptionPropertyBuilder extends AbstractPropertyBuilder
20
{
21
    /**
22
     * @var string
23
     */
24
    private $optionPropertyPrefix;
25
26
    /**
27
     * @param string $optionPropertyPrefix
28
     */
29
    public function __construct(string $optionPropertyPrefix)
30
    {
31
        $this->optionPropertyPrefix = $optionPropertyPrefix;
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->resolveProductOptions($product, $document);
49
    }
50
51
    /**
52
     * @param ProductInterface $product
53
     * @param Document $document
54
     */
55
    private function resolveProductOptions(ProductInterface $product, Document $document): void
56
    {
57
        foreach ($product->getVariants() as $productVariant) {
58
            foreach ($productVariant->getOptionValues() as $productOptionValue) {
59
                $optionCode = $productOptionValue->getOption()->getCode();
60
                $index = $this->optionPropertyPrefix . '_' . $optionCode;
61
62
                if (!$document->has($index)) {
63
                    $document->set($index, []);
64
                }
65
66
                $reference = $document->get($index);
67
                $value = $productOptionValue->getValue();
68
69
                if (!in_array($value, $reference)) {
70
                    $reference[] = $productOptionValue->getValue();
71
72
                    $document->set($index, $reference);
73
                }
74
            }
75
        }
76
    }
77
}
78