OptionBuilder   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 36
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveProductOptions() 0 11 4
A consumeEvent() 0 7 1
A __construct() 0 4 1
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\Formatter\StringFormatterInterface;
14
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\ConcatedNameResolverInterface;
15
use Elastica\Document;
16
use FOS\ElasticaBundle\Event\PostTransformEvent;
17
use Sylius\Component\Core\Model\ProductInterface;
18
19
final class OptionBuilder extends AbstractBuilder
20
{
21
    /** @var ConcatedNameResolverInterface */
22
    private $optionNameResolver;
23
24
    /** @var StringFormatterInterface */
25
    private $stringFormatter;
26
27
    public function __construct(ConcatedNameResolverInterface $optionNameResolver, StringFormatterInterface $stringFormatter)
28
    {
29
        $this->optionNameResolver = $optionNameResolver;
30
        $this->stringFormatter = $stringFormatter;
31
    }
32
33
    public function consumeEvent(PostTransformEvent $event): void
34
    {
35
        $this->buildProperty(
36
            $event,
37
            ProductInterface::class,
38
            function (ProductInterface $product, Document $document): void {
39
                $this->resolveProductOptions($product, $document);
40
            }
41
        );
42
    }
43
44
    private function resolveProductOptions(ProductInterface $product, Document $document): void
45
    {
46
        foreach ($product->getVariants() as $productVariant) {
47
            foreach ($productVariant->getOptionValues() as $productOptionValue) {
48
                $optionCode = $productOptionValue->getOption()->getCode();
49
                $index = $this->optionNameResolver->resolvePropertyName($optionCode);
50
                $options = $document->has($index) ? $document->get($index) : [];
51
                $value = $this->stringFormatter->formatToLowercaseWithoutSpaces($productOptionValue->getValue());
52
                $options[] = $value;
53
54
                $document->set($index, array_values(array_unique($options)));
55
            }
56
        }
57
    }
58
}
59