Skip to content

Commit

Permalink
add cartable contract
Browse files Browse the repository at this point in the history
  • Loading branch information
milwad-dev committed Jun 30, 2024
1 parent 6c7f4ce commit 71b34b9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/Cartable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Binafy\LaravelCart;

interface Cartable
{
public function getPrice(): int;

public function getKey(): mixed;
}
11 changes: 9 additions & 2 deletions src/Models/Cart.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Binafy\LaravelCart\Models;

use Binafy\LaravelCart\Cartable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

Expand Down Expand Up @@ -43,6 +44,9 @@ public function items(): \Illuminate\Database\Eloquent\Relations\HasMany

// Scopes

/**
* @throws \Exception
*/
public function scopeFirstOrCreateWithStoreItems(
Builder $query,
Model $item,
Expand All @@ -52,10 +56,13 @@ public function scopeFirstOrCreateWithStoreItems(
if (is_null($userId)) {
$userId = auth()->id();
}
if (! $item instanceof Cartable) {
throw new \Exception('The item must be an instance of Cartable');
}

$cart = $query->firstOrCreate(['user_id' => $userId]);
$cartItem = new CartItem([
'itemable_id' => $item->id,
'itemable_id' => $item->getKey(),
'itemable_type' => $item::class,
'quantity' => $quantity,
]);
Expand All @@ -74,7 +81,7 @@ public function calculatedPriceByQuantity(): int
{
$totalPrice = 0;
foreach ($this->items()->get() as $item) {
$totalPrice += (int) $item->quantity * (int) $item->itemable->price;
$totalPrice += (int) $item->quantity * (int) $item->itemable->getPrice();
}

return $totalPrice;
Expand Down

0 comments on commit 71b34b9

Please sign in to comment.