89 lines
2.6 KiB
PHP
89 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services\System;
|
|
|
|
use App\Enums\Role as EnumsRole;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Spatie\Permission\Models\Role;
|
|
|
|
class RoleService
|
|
{
|
|
/**
|
|
* @param array{search: string, sort: string, direction: 'asc'|'desc'} $tableQuery
|
|
*/
|
|
public function paginateForIndex(array $tableQuery): LengthAwarePaginator
|
|
{
|
|
$query = Role::query()
|
|
->withCount('permissions')
|
|
->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
|
|
{
|
|
DB::transaction(function () use ($validated): void {
|
|
$role = Role::create([
|
|
'name' => Str::slug($validated['name']),
|
|
'guard_name' => 'web',
|
|
]);
|
|
|
|
if (! empty($validated['permissions'])) {
|
|
$role->syncPermissions($validated['permissions']);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $validated
|
|
*/
|
|
public function update(Role $role, array $validated): void
|
|
{
|
|
DB::transaction(function () use ($role, $validated): void {
|
|
// Protect developer and owner names from changing
|
|
$updateData = [];
|
|
if (! in_array($role->name, [EnumsRole::DEVELOPER->value, EnumsRole::OWNER->value], true)) {
|
|
$updateData['name'] = Str::slug($validated['name']);
|
|
}
|
|
$role->update($updateData);
|
|
|
|
$role->syncPermissions($validated['permissions'] ?? []);
|
|
});
|
|
}
|
|
|
|
public function delete(Role $role): void
|
|
{
|
|
if (in_array($role->name, [EnumsRole::DEVELOPER->value, EnumsRole::OWNER->value], true)) {
|
|
throw new \InvalidArgumentException('Role developer atau owner tidak dapat dihapus.');
|
|
}
|
|
|
|
$role->delete();
|
|
}
|
|
|
|
private function applySorting(Builder $query, string $sort, string $direction): void
|
|
{
|
|
if (in_array($sort, ['name'], true)) {
|
|
$query->orderBy($sort, $direction);
|
|
|
|
return;
|
|
}
|
|
|
|
$query->latest();
|
|
}
|
|
}
|