diff --git a/src/Cart.php b/src/Cart.php index 48ca8e3..3d15f33 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -2,6 +2,7 @@ namespace Wearepixel\Cart; +use Wearepixel\Cart\Exceptions\InvalidConditionException; use Wearepixel\Cart\Helpers\Helpers; use Wearepixel\Cart\Validators\CartItemValidator; use Wearepixel\Cart\Exceptions\InvalidItemException; @@ -296,6 +297,11 @@ public function clear() /** * Adds a condition to the cart */ + /** + * Adds a condition to the cart + * + * @throws InvalidConditionException + */ public function condition(array|CartCondition $condition): self { if (is_array($condition)) { @@ -306,7 +312,27 @@ public function condition(array|CartCondition $condition): self return $this; } - return $this->condition($condition); + if (! $condition instanceof CartCondition) { + throw new InvalidConditionException('Argument 1 must be an instance of \'Wearepixel\Cart\CartCondition\''); + } + + $conditions = $this->getConditions(); + + // Check if order has been applied + if ($condition->getOrder() == 0) { + $last = $conditions->last(); + $condition->setOrder(! is_null($last) ? $last->getOrder() + 1 : 1); + } + + $conditions->put($condition->getName(), $condition); + + $conditions = $conditions->sortBy(function ($condition, $key) { + return $condition->getOrder(); + }); + + $this->saveConditions($conditions); + + return $this; } /** diff --git a/tests/Unit/CartConditionsTest.php b/tests/Unit/CartConditionsTest.php index fee4f05..26e01b9 100644 --- a/tests/Unit/CartConditionsTest.php +++ b/tests/Unit/CartConditionsTest.php @@ -1077,13 +1077,13 @@ $this->cart->add($item); - $this->cart->addConditions([$shipping, $tax]); + $this->cart->condition([$shipping, $tax]); // let's prove first we have now two conditions in the cart expect($this->cart->getConditions()->count())->toEqual(2, 'Cart should have two conditions'); // now let's remove a specific condition by condition name - $this->cart->removeCondition('Tax'); + $this->cart->removeCartCondition('Tax'); // cart should have now only 1 condition expect($this->cart->getConditions()->count())->toEqual(1, 'Cart should have one condition');