master_template/app/Repositories/PermissionRepository.php

122 lines
3.3 KiB
PHP
Raw Normal View History

2024-06-23 11:17:56 +00:00
<?php
namespace App\Repositories;
use Illuminate\Support\Facades\Route;
use App\Repositories\PermissionInterface;
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 getRoleById($roleId)
{
return Role::with('permissions')->findOrFail($roleId);
}
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();
// dd($routes);
foreach ($routes as $route) {
$routeName = $route->getName();
$ignoreRoutes = [
'installer',
'LaravelUpdater',
'debugbar',
'login',
'register',
'logout',
'post',
'ignition',
'unisharp',
'userLogin',
'postLogin',
'postLogin',
'postresgistration',
'home',
'single',
'newsDetail',
'password',
'showHororscope',
'showInternational',
'showVideos',
'videoDetail',
'showAboutus',
'showArtilce',
'showProvinces',
'contact',
'sendEmail',
'verification',
'auth',
'upload',
'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 == 'editor') {
$role->givePermissionTo(Permission::all());
}
}
}
}