Passed
Push — master ( 1a7a28...c3773f )
by Mikołaj
03:50
created

SoldUnitsPropertyBuilder::consumeEvent()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 1
nop 1
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
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
use Sylius\Component\Order\Repository\OrderItemRepositoryInterface;
19
20
final class SoldUnitsPropertyBuilder extends AbstractBuilder
21
{
22
    /**
23
     * @var OrderItemRepositoryInterface
24
     */
25
    private $orderItemRepository;
26
27
    /**
28
     * @var string
29
     */
30
    private $soldUnitsProperty;
31
32
    /**
33
     * @param OrderItemRepositoryInterface $orderItemRepository
34
     * @param string $soldUnitsProperty
35
     */
36
    public function __construct(OrderItemRepositoryInterface $orderItemRepository, string $soldUnitsProperty)
37
    {
38
        $this->orderItemRepository = $orderItemRepository;
39
        $this->soldUnitsProperty = $soldUnitsProperty;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function consumeEvent(TransformEvent $event): void
46
    {
47
        $this->buildProperty($event, ProductInterface::class,
48
            function (ProductInterface $product, Document $document): void {
49
                $soldUnits = 0;
50
51
                foreach ($product->getVariants() as $productVariant) {
52
                    $soldUnits += count($this->orderItemRepository->findBy(['variant' => $productVariant]));
53
                }
54
55
                $document->set($this->soldUnitsProperty, $soldUnits);
56
            }
57
        );
58
    }
59
}
60