Completed
Push — master ( 155c16...880d18 )
by Kamil
26:05
created

OrderItemQuantityModifier::decreaseUnitsNumber()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 10
rs 9.4285
c 1
b 1
f 0
cc 3
eloc 5
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Component\Order\Modifier;
13
14
use Sylius\Component\Order\Factory\OrderItemUnitFactoryInterface;
15
use Sylius\Component\Order\Model\OrderItemInterface;
16
17
/**
18
 * @author Mateusz Zalewski <[email protected]>
19
 */
20
class OrderItemQuantityModifier implements OrderItemQuantityModifierInterface
21
{
22
    /**
23
     * @var OrderItemUnitFactoryInterface
24
     */
25
    private $orderItemUnitFactory;
26
27
    /**
28
     * @param OrderItemUnitFactoryInterface $orderItemUnitFactory
29
     */
30
    public function __construct(OrderItemUnitFactoryInterface $orderItemUnitFactory)
31
    {
32
        $this->orderItemUnitFactory = $orderItemUnitFactory;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function modify(OrderItemInterface $orderItem, $targetQuantity)
39
    {
40
        $currentQuantity = $orderItem->getQuantity();
41
        if (0 >= $targetQuantity || $currentQuantity === $targetQuantity) {
42
            return;
43
        }
44
45
        if ($targetQuantity < $currentQuantity) {
46
            $this->decreaseUnitsNumber($orderItem, $currentQuantity - $targetQuantity);
47
        } elseif ($targetQuantity > $currentQuantity) {
48
            $this->increaseUnitsNumber($orderItem, $targetQuantity - $currentQuantity);
49
        }
50
    }
51
52
    /**
53
     * @param OrderItemInterface $orderItem
54
     * @param int $increaseBy
55
     */
56
    private function increaseUnitsNumber(OrderItemInterface $orderItem, $increaseBy)
57
    {
58
        for ($i = 0; $i < $increaseBy; ++$i) {
59
            $this->orderItemUnitFactory->createForItem($orderItem);
60
        }
61
    }
62
63
    /**
64
     * @param OrderItemInterface $orderItem
65
     * @param int $decreaseBy
66
     */
67
    private function decreaseUnitsNumber(OrderItemInterface $orderItem, $decreaseBy)
68
    {
69
        foreach ($orderItem->getUnits() as $unit) {
70
            if (0 >= $decreaseBy--) {
71
                break;
72
            }
73
74
            $orderItem->removeUnit($unit);
75
        }
76
    }
77
}
78