OrderVoucherDistributor::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 1
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
 * You can find more information about us on https://bitbag.io and write us
7
 * an email on [email protected].
8
 */
9
10
declare(strict_types=1);
11
12
namespace BitBag\SyliusMolliePlugin\Distributor\Order;
13
14
use BitBag\SyliusMolliePlugin\Applicator\UnitsPromotionAdjustmentsApplicatorInterface;
15
use Sylius\Component\Core\Distributor\ProportionalIntegerDistributorInterface;
16
use Sylius\Component\Core\Model\OrderInterface;
17
18
final class OrderVoucherDistributor implements OrderVoucherDistributorInterface
19
{
20
    /** @var ProportionalIntegerDistributorInterface */
21
    private $proportionalIntegerDistributor;
22
23
    /** @var UnitsPromotionAdjustmentsApplicatorInterface */
24
    private $unitsPromotionAdjustmentsApplicator;
25
26
    public function __construct(
27
        ProportionalIntegerDistributorInterface $proportionalIntegerDistributor,
28
        UnitsPromotionAdjustmentsApplicatorInterface $unitsPromotionAdjustmentsApplicator
29
    ) {
30
        $this->proportionalIntegerDistributor = $proportionalIntegerDistributor;
31
        $this->unitsPromotionAdjustmentsApplicator = $unitsPromotionAdjustmentsApplicator;
32
    }
33
34
    public function distribute(OrderInterface $order, int $amount): void
35
    {
36
        $promotionAmount = $this->calculateAdjustmentAmount(
37
            $order->getPromotionSubjectTotal(),
38
            $amount
39
        );
40
41
        if (0 === $promotionAmount) {
42
            return;
43
        }
44
45
        $itemsTotals = [];
46
        foreach ($order->getItems() as $item) {
47
            $itemsTotals[] = $item->getTotal();
48
        }
49
50
        $splitPromotion = $this->proportionalIntegerDistributor->distribute($itemsTotals, $promotionAmount);
51
        $this->unitsPromotionAdjustmentsApplicator->apply($order, $splitPromotion);
52
    }
53
54
    private function calculateAdjustmentAmount(int $promotionSubjectTotal, int $targetPromotionAmount): int
55
    {
56
        return -1 * min($promotionSubjectTotal, $targetPromotionAmount);
57
    }
58
}
59