90 lines
2.2 KiB
PHP
90 lines
2.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Database;
|
|
|
|
class ItemModel
|
|
{
|
|
public static function create(int $listId, array $data): array
|
|
{
|
|
$insertData = [
|
|
'list_id' => $listId,
|
|
'name' => $data['name'] ?? '',
|
|
'category' => $data['category'] ?? null,
|
|
'quantity' => $data['quantity'] ?? 1.0,
|
|
];
|
|
|
|
$id = Database::insert('items', $insertData);
|
|
|
|
return self::findById($id);
|
|
}
|
|
|
|
public static function findById(int $id): ?array
|
|
{
|
|
$item = Database::selectOne('items', ['id' => $id]);
|
|
|
|
if ($item) {
|
|
$item['quantity'] = (float) $item['quantity'];
|
|
}
|
|
|
|
return $item;
|
|
}
|
|
|
|
public static function findByListId(int $listId): array
|
|
{
|
|
$items = Database::query(
|
|
'SELECT * FROM items WHERE list_id = :list_id AND deleted_at IS NULL ORDER BY created_at DESC',
|
|
['list_id' => $listId]
|
|
);
|
|
|
|
foreach ($items as &$item) {
|
|
$item['quantity'] = (float) $item['quantity'];
|
|
}
|
|
|
|
return $items;
|
|
}
|
|
|
|
public static function update(int $listId, int $itemId, array $data): ?array
|
|
{
|
|
$item = Database::selectOne('items', ['id' => $itemId, 'list_id' => $listId]);
|
|
|
|
if (!$item) {
|
|
return null;
|
|
}
|
|
|
|
$updateData = [];
|
|
|
|
if (isset($data['name'])) {
|
|
$updateData['name'] = $data['name'];
|
|
}
|
|
|
|
if (isset($data['category'])) {
|
|
$updateData['category'] = $data['category'];
|
|
}
|
|
|
|
if (isset($data['quantity'])) {
|
|
$updateData['quantity'] = $data['quantity'];
|
|
}
|
|
|
|
if (empty($updateData)) {
|
|
return self::findById($itemId);
|
|
}
|
|
|
|
Database::update('items', $updateData, ['id' => $itemId, 'list_id' => $listId]);
|
|
|
|
return self::findById($itemId);
|
|
}
|
|
|
|
public static function delete(int $listId, int $itemId): bool
|
|
{
|
|
$updated = Database::execute(
|
|
'UPDATE items SET deleted_at = CURRENT_TIMESTAMP WHERE id = :id AND list_id = :list_id AND deleted_at IS NULL',
|
|
['id' => $itemId, 'list_id' => $listId]
|
|
);
|
|
|
|
return $updated > 0;
|
|
}
|
|
}
|