diff --git a/src/Domain/Cart.php b/src/Domain/Cart.php index 5522428..66d4749 100644 --- a/src/Domain/Cart.php +++ b/src/Domain/Cart.php @@ -12,7 +12,12 @@ class Cart public function add(string $productId, Price $unitPrice, int $amount = 1) { - $this->items[] = new Item($productId, $unitPrice, $amount); + try { + $item = $this->find($productId); + $item->add($amount); + } catch (ProductNotInCartException $e) { + $this->items[] = new Item($productId, $unitPrice, $amount); + } } public function remove(string $productId) @@ -35,4 +40,17 @@ public function calculate(): CartDetail return new CartDetail($detailItems, new Price($totalPrice)); } + + /** + * @throws ProductNotInCartException + */ + private function find(string $productId): Item + { + foreach ($this->items as $item) { + if ($item->getProductId() === $productId) { + return $item; + } + } + throw new ProductNotInCartException(); + } } diff --git a/src/Domain/Item.php b/src/Domain/Item.php index 26beaa9..5391dc4 100644 --- a/src/Domain/Item.php +++ b/src/Domain/Item.php @@ -33,6 +33,11 @@ public function toDetail(): DetailItem return new DetailItem($this->productId, $this->unitPrice, $this->amount); } + public function getProductId(): string + { + return $this->productId; + } + public function add(int $amount) { $this->checkAmount($amount); diff --git a/src/Domain/ProductNotInCartException.php b/src/Domain/ProductNotInCartException.php new file mode 100644 index 0000000..8be6385 --- /dev/null +++ b/src/Domain/ProductNotInCartException.php @@ -0,0 +1,10 @@ +