- schema for cart and product - define relationship, DTO, Resource and API collections - Add post and get endpoint for cart api
50 lines
1.4 KiB
PHP
50 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Data;
|
|
|
|
use App\Contracts\OutputDataTransferObject;
|
|
use App\Models\Cart;
|
|
|
|
final readonly class CartDTO implements OutputDataTransferObject
|
|
{
|
|
/**
|
|
* @param CartItemDTO[] $items
|
|
*/
|
|
public function __construct(
|
|
public int $id,
|
|
public ?int $itemsCount = null,
|
|
public ?int $totalPrice = null,
|
|
public array $items = []
|
|
) {}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toArray(): array
|
|
{
|
|
return [
|
|
'id' => $this->id,
|
|
'itemsCount' => $this->itemsCount,
|
|
'totalPrice' => $this->totalPrice,
|
|
'items' => $this->items,
|
|
];
|
|
}
|
|
|
|
public static function fromModel(Cart $cart)
|
|
{
|
|
return new self(
|
|
id: $cart->id,
|
|
itemsCount: $cart->products->count(),
|
|
totalPrice: $cart->products->sum(fn ($product) => $product->pivot->price * $product->pivot->quantity),
|
|
items: $cart->products->map(fn ($product) => new CartItemDTO(
|
|
id: $product->id,
|
|
title: $product->title,
|
|
quantity: $product->pivot->quantity,
|
|
price: $product->actual_price,
|
|
subtotal: $product->actual_price * $product->pivot->quantity,
|
|
image: $product->images->first()->path,
|
|
))->toArray()
|
|
);
|
|
}
|
|
}
|