StocksNew/Modules/User/app/Repositories/PermissionRepository.php
Sampanna Rimal 53c0140f58 first commit
2024-08-27 17:48:06 +05:45

92 lines
2.4 KiB
PHP

<?php
namespace Modules\User\Repositories;
use Illuminate\Support\Facades\Route;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class PermissionRepository implements PermissionInterface
{
public function findAll()
{
return Permission::get();
}
public function getPermissionById($permissionId)
{
return Permission::findOrFail($permissionId);
}
public function delete($permissionId)
{
Permission::destroy($permissionId);
}
public function create(array $permissionDetails)
{
return Permission::create($permissionDetails);
}
public function update($permissionId, array $newDetails)
{
return Permission::where('id', $permissionId)->update($newDetails);
}
public function getPermissionListsArrangedByPrefix()
{
$permissions = self::findAll();
$routeNameArr = [];
foreach ($permissions as $permission) {
if (!is_null($permission->name)) {
$routeName = explode('.', $permission->name);
if (is_array($routeName) && !empty($routeName[0])) {
$routeNameArr[$routeName[0]][$permission->id] = array_key_exists(1, $routeName) ? $routeName[1] : $routeName[0];
}
}
}
return $routeNameArr;
}
public static function generatePermissionFromRoutes()
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
$routeName = $route->getName();
$ignoreRoutes = [
'debugbar',
'login',
'register',
'logout',
'post',
'sanctum',
'ignition',
'welcome',
'home',
'api'
];
$routePrefix = explode('.', $routeName);
if (is_array($routePrefix) && !empty($routePrefix[0])) {
if (!in_array($routePrefix[0], $ignoreRoutes) && !Permission::where('name', $routeName)->exists()) {
Permission::create(['name' => $routeName, 'guard_name' => 'web']);
}
}
}
$roles = Role::all();
foreach ($roles as $role) {
if ($role->name == 'admin' || $role->name == 'super-admin') {
$role->givePermissionTo(Permission::all());
}
}
}
}