63 lines
1.9 KiB
PHP
63 lines
1.9 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 $slug,
|
|
public string $description,
|
|
public int $actualPrice,
|
|
public int $listPrice,
|
|
public ProductCategoryDTO $category,
|
|
public array $productImages,
|
|
public ?string $updatedAt = null,
|
|
public ?string $createdAt = null,
|
|
) {}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toArray(): array
|
|
{
|
|
return [
|
|
'id' => $this->id,
|
|
'title' => $this->title,
|
|
'slug' => $this->slug,
|
|
'description' => $this->description,
|
|
'actualPrice' => $this->actualPrice,
|
|
'listPrice' => $this->listPrice,
|
|
'category' => $this->category->toArray(),
|
|
'productImage' => array_map(fn (ProductImageDTO $productImage) => $productImage->toArray(),
|
|
$this->productImages),
|
|
'updatedAt' => $this->updatedAt,
|
|
'createdAt' => $this->createdAt,
|
|
];
|
|
}
|
|
|
|
public static function fromModel(Product $product): self
|
|
{
|
|
return new self(
|
|
id: $product->id,
|
|
title: $product->title,
|
|
slug: $product->slug,
|
|
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(),
|
|
updatedAt: $product->updated_at,
|
|
createdAt: $product->created_at,
|
|
);
|
|
}
|
|
}
|