feat: refactor cart and purchase handling to support polymorphic buyable types and improve code readability
This commit is contained in:
@@ -2,13 +2,16 @@
|
||||
|
||||
namespace App\Domains\Purchase\Resources;
|
||||
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Purchase\Models\PurchaseItem|\App\Domains\Cart\Models\CartItem
|
||||
* @mixin PurchaseItem|CartItem
|
||||
*/
|
||||
class PurchaseItemResource extends JsonResource
|
||||
{
|
||||
@@ -17,15 +20,16 @@ class PurchaseItemResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
|
||||
/** @var Buyable|null $buyable */
|
||||
$buyable = $this->buyable;
|
||||
$quantity = (int) ($this->cantidad ?? 0);
|
||||
$unitPrice = $this->resolveUnitPrice();
|
||||
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
|
||||
$variant = $buyable instanceof ProductVariant ? $buyable : null;
|
||||
|
||||
$imageUrl = null;
|
||||
$attributes = [];
|
||||
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable) {
|
||||
if ($this->buyable_type === ProductVariant::class && $buyable) {
|
||||
$imageUrl = $this->resolveImageUrl($buyable);
|
||||
$attributes = $this->resolveAttributes($buyable);
|
||||
}
|
||||
@@ -37,6 +41,16 @@ class PurchaseItemResource extends JsonResource
|
||||
'line_total' => $this->formatMoney($lineTotal),
|
||||
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
|
||||
'buyable_id' => $this->buyable_id,
|
||||
'product' => $variant === null ? null : [
|
||||
'id' => $variant->product?->id,
|
||||
'nombre' => $variant->product?->nombre,
|
||||
'slug' => $variant->product?->slug,
|
||||
'imagen' => $imageUrl,
|
||||
],
|
||||
'variant' => $variant === null ? null : [
|
||||
'id' => $variant->id,
|
||||
'attributes' => $attributes,
|
||||
],
|
||||
'item_details' => $buyable === null ? null : [
|
||||
'nombre' => $buyable->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
@@ -48,8 +62,8 @@ class PurchaseItemResource extends JsonResource
|
||||
protected function mapBuyableTypeToAlias(?string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
|
||||
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
|
||||
ProductVariant::class => 'variant',
|
||||
Bundle::class => 'bundle',
|
||||
default => 'unknown',
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user