Passed
Push — master ( ffdb0e...58b9a2 )
by Mikołaj
03:54
created

SoldUnitsPropertyBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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 FOS\ElasticaBundle\Event\TransformEvent;
16
use Sylius\Component\Core\Model\ProductInterface;
17
use Sylius\Component\Order\Repository\OrderItemRepositoryInterface;
18
19
final class SoldUnitsPropertyBuilder extends AbstractBuilder
20
{
21
    /**
22
     * @var OrderItemRepositoryInterface
23
     */
24
    private $orderItemRepository;
25
26
    /**
27
     * @var string
28
     */
29
    private $soldUnitsProperty;
30
31
    /**
32
     * @param OrderItemRepositoryInterface $orderItemRepository
33
     * @param string $soldUnitsProperty
34
     */
35
    public function __construct(OrderItemRepositoryInterface $orderItemRepository, string $soldUnitsProperty)
36
    {
37
        $this->orderItemRepository = $orderItemRepository;
38
        $this->soldUnitsProperty = $soldUnitsProperty;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function buildProperty(TransformEvent $event): void
45
    {
46
        /** @var ProductInterface $product */
47
        $product = $event->getObject();
48
49
        if (!$product instanceof ProductInterface) {
0 ignored issues
show
introduced by
$product is always a sub-type of Sylius\Component\Core\Model\ProductInterface.
Loading history...
50
            return;
51
        }
52
53
        $soldUnits = 0;
54
55
        foreach ($product->getVariants() as $productVariant) {
56
            $soldUnits += count($this->orderItemRepository->findBy(['variant' => $productVariant]));
57
        }
58
59
        $event->getDocument()->set($this->soldUnitsProperty, $soldUnits);
60
    }
61
}
62