- implement DTO for product and modify productImageDTO. - add products resources and collection.
54 lines
1.6 KiB
PHP
54 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Data;
|
|
|
|
use App\Contracts\OutputDataTransferObject;
|
|
use App\Models\Product;
|
|
use App\Models\ProductImage;
|
|
|
|
final readonly class ProductDTO implements OutputDataTransferObject
|
|
{
|
|
/**
|
|
* @param ProductImageDTO[] $productImages
|
|
*/
|
|
public function __construct(
|
|
public int $id,
|
|
public string $title,
|
|
public string $description,
|
|
public int $actualPrice,
|
|
public int $listPrice,
|
|
public ProductCategoryDTO $category,
|
|
public array $productImages,
|
|
) {}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toArray(): array
|
|
{
|
|
return [
|
|
'id' => $this->id,
|
|
'title' => $this->title,
|
|
'description' => $this->description,
|
|
'actualPrice' => $this->actualPrice,
|
|
'listPrice' => $this->listPrice,
|
|
'category' => $this->category->toArray(),
|
|
'productImage' => array_map(fn (ProductImageDTO $productImage) => $productImage->toArray(),
|
|
$this->productImages),
|
|
];
|
|
}
|
|
|
|
public static function fromModel(Product $product): self
|
|
{
|
|
return new self(
|
|
id: $product->id,
|
|
title: $product->title,
|
|
description: $product->description,
|
|
actualPrice: $product->actual_price,
|
|
listPrice: $product->list_price,
|
|
category: ProductCategoryDTO::fromModel($product->category),
|
|
productImages: $product->images->map(fn (ProductImage $productImage) => ProductImageDTO::fromModel($productImage))->all(),
|
|
);
|
|
}
|
|
}
|