Skip to content

Commit

Permalink
Implement adding same product
Browse files Browse the repository at this point in the history
  • Loading branch information
simara-svatopluk committed Dec 17, 2017
1 parent dfe0f01 commit c6a15dc
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Domain/Cart.php
Expand Up @@ -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)
Expand All @@ -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();
}
}
5 changes: 5 additions & 0 deletions src/Domain/Item.php
Expand Up @@ -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);
Expand Down
10 changes: 10 additions & 0 deletions src/Domain/ProductNotInCartException.php
@@ -0,0 +1,10 @@
<?php

namespace Simara\Cart\Domain;

use DomainException;

class ProductNotInCartException extends DomainException
{

}

0 comments on commit c6a15dc

Please sign in to comment.