[Order] Ensure correct item in post_add event

This commit is contained in:
Jan Goralski 2023-03-15 16:51:59 +01:00
parent 770ea40244
commit 814df1e110
No known key found for this signature in database
GPG key ID: 95D91BA380F31EDD
2 changed files with 16 additions and 2 deletions

View file

@ -42,3 +42,9 @@ Feature: Adding a simple product to the cart
And I should be notified that the product has been successfully added
And there should be one item in my cart
And this item should have name "T-Shirt banana"
@ui @api
Scenario: Increasing quantity of an item in cart by adding the product again
Given I have product "T-Shirt banana" in the cart
When I add this product to the cart
Then I should see "T-Shirt banana" with quantity 2 in my cart

View file

@ -54,8 +54,9 @@ class OrderItemController extends ResourceController
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
/** @var AddToCartCommandInterface $addToCartCommand */
$addToCartCommand = $form->getData();
[$cart, $orderItem] = [$addToCartCommand->getCart(), $addToCartCommand->getCartItem()];
$errors = $this->getCartItemErrors($addToCartCommand->getCartItem());
$errors = $this->getCartItemErrors($orderItem);
if (0 < count($errors)) {
$form = $this->getAddToCartFormWithErrors($errors, $form);
@ -73,12 +74,14 @@ class OrderItemController extends ResourceController
return $this->redirectHandler->redirectToIndex($configuration, $orderItem);
}
$this->getOrderModifier()->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
$this->getOrderModifier()->addToOrder($cart, $orderItem);
$cartManager = $this->getCartManager();
$cartManager->persist($cart);
$cartManager->flush();
$orderItem = $this->resolveAddedOrderItem($cart, $orderItem);
$resourceControllerEvent = $this->eventDispatcher->dispatchPostEvent(CartActions::ADD, $configuration, $orderItem);
if ($resourceControllerEvent->hasResponse()) {
return $resourceControllerEvent->getResponse();
@ -242,4 +245,9 @@ class OrderItemController extends ResourceController
View::create($form, Response::HTTP_BAD_REQUEST)->setData(['errors' => $form->getErrors(true, true)]),
);
}
protected function resolveAddedOrderItem(OrderInterface $order, OrderItemInterface $item): OrderItemInterface
{
return $order->getItems()->filter(fn (OrderItemInterface $orderItem): bool => $orderItem->equals($item))->first();
}
}