Skip to content

Commit

Permalink
Merge pull request #35 from binafy/change-int-to-float-for-calculated…
Browse files Browse the repository at this point in the history
…PriceByQuantity

[1.x] Change int to float for calculated price by quantity
  • Loading branch information
milwad-dev authored Jan 26, 2025
2 parents b1c3c65 + bf23142 commit c24e107
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Models/Cart.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,11 @@ public function scopeFirstOrCreateWithStoreItems(
/**
* Calculate price by quantity of items.
*/
public function calculatedPriceByQuantity(): int
public function calculatedPriceByQuantity(): float
{
$totalPrice = 0;
foreach ($this->items()->get() as $item) {
$totalPrice += (int) $item->quantity * (int) $item->itemable->getPrice();
$totalPrice += (int) $item->quantity * (float) $item->itemable->getPrice();
}

return $totalPrice;
Expand Down
14 changes: 12 additions & 2 deletions tests/Feature/Models/CartStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use function Pest\Laravel\assertDatabaseCount;
use function Pest\Laravel\assertDatabaseHas;
use function Pest\Laravel\assertDatabaseMissing;
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertInstanceOf;

/*
Expand Down Expand Up @@ -188,11 +189,20 @@
$cart->storeItems($items);

// Assertions
\PHPUnit\Framework\assertEquals(230000, $cart->calculatedPriceByQuantity());
assertEquals(230000, $cart->calculatedPriceByQuantity());

// Float
$cart->storeItems([
[
'itemable' => Product::query()->create(['title' => 'Product float', 'price' => 15000.3]),
'quantity' => 2,
],
]);
assertEquals(260000.6, $cart->calculatedPriceByQuantity());

// DB Assertions
assertDatabaseCount('carts', 1);
assertDatabaseCount('cart_items', 3);
assertDatabaseCount('cart_items', 4);
assertDatabaseHas('cart_items', [
'itemable_id' => $product1->id,
'itemable_type' => $product1::class,
Expand Down

0 comments on commit c24e107

Please sign in to comment.