1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Sylius\ShopApiPlugin\Modifier; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\Persistence\ObjectManager; |
8
|
|
|
use Sylius\Component\Core\Factory\CartItemFactoryInterface; |
9
|
|
|
use Sylius\Component\Core\Model\OrderInterface; |
10
|
|
|
use Sylius\Component\Core\Model\OrderItemInterface; |
11
|
|
|
use Sylius\Component\Core\Model\ProductVariantInterface; |
12
|
|
|
use Sylius\Component\Order\Modifier\OrderItemQuantityModifierInterface; |
13
|
|
|
use Sylius\Component\Order\Processor\OrderProcessorInterface; |
14
|
|
|
|
15
|
|
|
final class OrderModifier implements OrderModifierInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var CartItemFactoryInterface |
19
|
|
|
*/ |
20
|
|
|
private $cartItemFactory; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var OrderItemQuantityModifierInterface |
24
|
|
|
*/ |
25
|
|
|
private $orderItemQuantityModifier; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var OrderProcessorInterface |
29
|
|
|
*/ |
30
|
|
|
private $orderProcessor; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var ObjectManager |
34
|
|
|
*/ |
35
|
|
|
private $orderManager; |
36
|
|
|
|
37
|
|
|
public function __construct( |
38
|
|
|
CartItemFactoryInterface $cartItemFactory, |
39
|
|
|
OrderItemQuantityModifierInterface $orderItemQuantityModifier, |
40
|
|
|
OrderProcessorInterface $orderProcessor, |
41
|
|
|
ObjectManager $orderManager |
42
|
|
|
) { |
43
|
|
|
$this->cartItemFactory = $cartItemFactory; |
44
|
|
|
$this->orderItemQuantityModifier = $orderItemQuantityModifier; |
45
|
|
|
$this->orderProcessor = $orderProcessor; |
46
|
|
|
$this->orderManager = $orderManager; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function modify(OrderInterface $order, ProductVariantInterface $productVariant, int $quantity): void |
50
|
|
|
{ |
51
|
|
|
$cartItem = $this->getCartItemToModify($order, $productVariant); |
52
|
|
|
if (null !== $cartItem) { |
53
|
|
|
$this->orderItemQuantityModifier->modify($cartItem, $cartItem->getQuantity() + $quantity); |
54
|
|
|
$this->orderProcessor->process($order); |
55
|
|
|
|
56
|
|
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$cartItem = $this->cartItemFactory->createForCart($order); |
60
|
|
|
$cartItem->setVariant($productVariant); |
61
|
|
|
$this->orderItemQuantityModifier->modify($cartItem, $quantity); |
62
|
|
|
|
63
|
|
|
$order->addItem($cartItem); |
64
|
|
|
|
65
|
|
|
$this->orderProcessor->process($order); |
66
|
|
|
|
67
|
|
|
$this->orderManager->persist($order); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
private function getCartItemToModify(OrderInterface $cart, ProductVariantInterface $productVariant): ?OrderItemInterface |
71
|
|
|
{ |
72
|
|
|
/** @var OrderItemInterface $cartItem */ |
73
|
|
|
foreach ($cart->getItems() as $cartItem) { |
74
|
|
|
if ($productVariant === $cartItem->getVariant()) { |
75
|
|
|
return $cartItem; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return null; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|