ekart/backend/app/Data/ProductDTO.php
kusowl ae008fbc9c chore: add isFavorite in produtcs response
- refactor code to use query
- add active column in products
2026-03-05 13:32:49 +05:30

67 lines
2.1 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,
public ?bool $isFavorite = 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,
'isFavorite' => $this->isFavorite,
];
}
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,
// this column is added by where exists query
isFavorite: $product->favorited_by_exists,
);
}
}