From 503e489a423f1805d979799dd0566d3d541d20e0 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Tue, 30 Apr 2024 16:06:25 +0100 Subject: [PATCH] Handle cart line update validation (#1718) --- .../Validation/CartLine/CartLineQuantity.php | 8 +++++ .../CartLine/CartLineQuantityTest.php | 29 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/packages/core/src/Validation/CartLine/CartLineQuantity.php b/packages/core/src/Validation/CartLine/CartLineQuantity.php index 30a627a095..7c2d385e86 100644 --- a/packages/core/src/Validation/CartLine/CartLineQuantity.php +++ b/packages/core/src/Validation/CartLine/CartLineQuantity.php @@ -13,6 +13,14 @@ public function validate(): bool { $quantity = $this->parameters['quantity'] ?? 0; $purchasable = $this->parameters['purchasable'] ?? null; + $cartLineId = $this->parameters['cartLineId'] ?? null; + $cart = $this->parameters['cart'] ?? null; + + if ($cartLineId && ! $purchasable && $cart) { + $purchasable = $cart->lines->first( + fn ($cartLine) => $cartLine->id == $cartLineId + )?->purchasable; + } if ($quantity < 1) { $this->fail( diff --git a/tests/core/Unit/Validation/CartLine/CartLineQuantityTest.php b/tests/core/Unit/Validation/CartLine/CartLineQuantityTest.php index 2dfc925de3..5c53d78b13 100644 --- a/tests/core/Unit/Validation/CartLine/CartLineQuantityTest.php +++ b/tests/core/Unit/Validation/CartLine/CartLineQuantityTest.php @@ -164,3 +164,32 @@ 'increment' => 14, ], ]); + +test('can validate from cart line id', function () { + $currency = Currency::factory()->create(); + + $cart = Cart::factory()->create([ + 'currency_id' => $currency->id, + ]); + + $purchasable = \Lunar\Models\ProductVariant::factory()->create([ + 'quantity_increment' => 25, + ]); + + $cart->lines()->create([ + 'purchasable_type' => \Lunar\Models\ProductVariant::class, + 'purchasable_id' => $purchasable->id, + 'quantity' => 50, + ]); + + $validator = (new CartLineQuantity)->using( + cart: $cart, + purchasable: null, + cartLineId: $cart->lines()->first()->id, + quantity: 26, + meta: [] + ); + + expect(fn () => $validator->validate()) + ->toThrow(CartException::class); +});