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

OrderItemQuantityModifier   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 11
lcom 1
cbo 2
dl 0
loc 58
rs 10
c 1
b 1
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B modify() 0 13 5
A increaseUnitsNumber() 0 6 2
A decreaseUnitsNumber() 0 10 3
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