From cb470f69a387feb5d3eb642ca41c348273d9c43b Mon Sep 17 00:00:00 2001 From: Andrew Savchenko Date: Thu, 31 Oct 2019 21:04:34 +0100 Subject: [PATCH 1/3] Fix products sequence after changing cart item options --- src/Cart.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Cart.php b/src/Cart.php index 97097a0..17cbb3a 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -180,6 +180,8 @@ class Cart $content = $this->getContent(); if ($rowId !== $cartItem->rowId) { + $itemOldIndex = $content->keys()->search($rowId); + $content->pull($rowId); if ($content->has($cartItem->rowId)) { @@ -193,7 +195,14 @@ class Cart return; } else { - $content->put($cartItem->rowId, $cartItem); + if (isset($itemOldIndex)) + { + $content = $content->slice(0, $itemOldIndex) + ->merge([$cartItem->rowId => $cartItem]) + ->merge($content->slice($itemOldIndex)); + } else { + $content->put($cartItem->rowId, $cartItem); + } } $this->events->dispatch('cart.updated', $cartItem); From 5d7aee42d7e2fd4b00f46b69e62c81ed3d9f48b4 Mon Sep 17 00:00:00 2001 From: Andrew Savchenko Date: Thu, 31 Oct 2019 21:33:05 +0100 Subject: [PATCH 2/3] Fix code style --- src/Cart.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Cart.php b/src/Cart.php index 17cbb3a..7f2445d 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -195,8 +195,7 @@ class Cart return; } else { - if (isset($itemOldIndex)) - { + if (isset($itemOldIndex)) { $content = $content->slice(0, $itemOldIndex) ->merge([$cartItem->rowId => $cartItem]) ->merge($content->slice($itemOldIndex)); From e4e9a6ec6ebbcad8a4682dff7f957aca3532d2ec Mon Sep 17 00:00:00 2001 From: Andrew Savchenko Date: Sat, 2 Nov 2019 14:29:54 +0100 Subject: [PATCH 3/3] Add a test case to assert items sequence is kept if the options changed --- tests/CartTest.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/CartTest.php b/tests/CartTest.php index e9acea9..5c7d8e5 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -399,6 +399,21 @@ class CartTest extends TestCase $this->assertRowsInCart(1, $cart); } + /** @test */ + public function it_will_keep_items_sequence_if_the_options_changed() + { + $cart = $this->getCart(); + + $cart->add(new BuyableProduct(), 1, ['color' => 'red']); + $cart->add(new BuyableProduct(), 1, ['color' => 'green']); + $cart->add(new BuyableProduct(), 1, ['color' => 'blue']); + + $cart->update($cart->content()->values()[1]->rowId, ['options' => ['color' => 'yellow']]); + + $this->assertRowsInCart(3, $cart); + $this->assertEquals('yellow', $cart->content()->values()[1]->options->color); + } + /** @test */ public function it_can_remove_an_item_from_the_cart() {