File: /var/www/matriculas_api_dev/app/Services/ProfileService.php
<?php
namespace App\Services;
use App\Http\Resources\ProfileResource;
use App\Repositories\ProfileRepository;
use App\Repositories\PermissionRepository;
use Exception;
class ProfileService
{
protected $profileRepository;
protected $permissionRepository;
public function __construct(
ProfileRepository $profileRepository,
PermissionRepository $permissionRepository
) {
$this->profileRepository = $profileRepository;
$this->permissionRepository = $permissionRepository;
}
public function list($allData = true)
{
$registers = $this->profileRepository->getAllWithPermissions();
if ($registers->count() < 1) {
return [];
}
return ProfileResource::collection($registers)->resolve();
}
public function store($request)
{
$code = getSlug($request->profile, true, '_');
$validateField = $this->profileRepository->getByCode($code);
if ($validateField) {
throw new Exception("Perfil ya existe en la base de datos", 409);
}
$request->code = $code;
$register = $this->profileRepository->create((object)$request);
if (!$register) {
throw new Exception("Ocurrió un problema al registrar", 500);
}
return $this->show($register->id, false);
}
public function update($request, $id)
{
$register = $this->show($id, true);
$code = getSlug($request->profile, true, '_');
$validateField = $this->profileRepository->getByCode($code, $id);
if ($validateField) {
throw new Exception("Perfil ya existe en la base de datos", 409);
}
$request->code = $code;
$update = $this->profileRepository->update($register, $request);
if (!$update) {
throw new Exception("Ocurrió un problema al actualizar registro", 500);
}
return $update;
}
public function show($id, $allData = false)
{
$register = $this->profileRepository->getById($id);
if (!$register) {
throw new Exception("Perfil no existe o fue eliminado", 400);
}
if ($allData) {
return $register;
}
return (object)(new ProfileResource($register))->resolve();
}
public function delete($id)
{
if ($id == auth()->user()->profile_id) {
throw new Exception("No es posible eliminar tu propio perfil", 500);
}
$register = $this->show($id, true);
$register->deleted = 1;
$register->deleted_at = now();
$register->user_deleted = auth()->user()->id;
if (!$register->save()) {
throw new Exception("Ocurrió un problema al eliminar registro", 500);
}
return true;
}
/**
* Update permissions matrix for all profiles
*/
public function updatePermissionsMatrix($profilesMatrix)
{
if (!is_array($profilesMatrix)) {
throw new Exception("El formato de la matriz de permisos no es válido", 400);
}
return $this->profileRepository->updatePermissionsMatrix($profilesMatrix);
}
/**
* Get all permissions grouped by category
*/
public function getPermissions()
{
return $this->permissionRepository->getAllGroupedByCategory();
}
}