80 lines
2.1 KiB
PHP
80 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Master;
|
|
|
|
use App\Jobs\SendPushNotificationJob;
|
|
use App\Models\Category;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
|
|
class CategoryService
|
|
{
|
|
/**
|
|
* @param array{search: string, sort: string, direction: 'asc'|'desc'} $tableQuery
|
|
*/
|
|
public function paginateForIndex(array $tableQuery): LengthAwarePaginator
|
|
{
|
|
$query = Category::query()
|
|
->when($tableQuery['search'] !== '', function (Builder $query) use ($tableQuery): void {
|
|
$search = $tableQuery['search'];
|
|
$query->where(function (Builder $query) use ($search): void {
|
|
$query->where('name', 'like', "%{$search}%");
|
|
});
|
|
});
|
|
|
|
$this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);
|
|
|
|
return $query
|
|
->paginate(10)
|
|
->withQueryString();
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $validated
|
|
*/
|
|
public function create(array $validated): void
|
|
{
|
|
$category = Category::create($validated);
|
|
|
|
SendPushNotificationJob::dispatch(
|
|
'📦 Kategori Baru',
|
|
"Kategori '{$category->name}' telah ditambahkan.",
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $validated
|
|
*/
|
|
public function update(Category $category, array $validated): void
|
|
{
|
|
$category->fill($validated)->save();
|
|
|
|
SendPushNotificationJob::dispatch(
|
|
'✏️ Kategori Diperbarui',
|
|
"Kategori '{$category->name}' telah diperbarui.",
|
|
);
|
|
}
|
|
|
|
public function delete(Category $category): void
|
|
{
|
|
$name = $category->name;
|
|
$category->delete();
|
|
|
|
SendPushNotificationJob::dispatch(
|
|
'🗑️ Kategori Dihapus',
|
|
"Kategori '{$name}' telah dihapus.",
|
|
);
|
|
}
|
|
|
|
private function applySorting(Builder $query, string $sort, string $direction): void
|
|
{
|
|
if (in_array($sort, ['name', 'slug'], true)) {
|
|
$query->orderBy($sort, $direction);
|
|
|
|
return;
|
|
}
|
|
|
|
$query->latest();
|
|
}
|
|
}
|