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
|
|
|
|