96 lines
2.3 KiB
PHP
96 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Permission;
|
|
|
|
use Dipper\Foundation\Core\Model;
|
|
use Illuminate\Support\Collection;
|
|
use App\Exceptions\NotExistException;
|
|
use App\Models\Permission\Traits\HasRoles;
|
|
use Dipper\Foundation\Nestedset\NodeTrait;
|
|
use App\Domains\Permission\Services\PermissionService;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use App\Models\Permission\Traits\RefreshesPermissionCache;
|
|
|
|
/**
|
|
* 权限
|
|
*/
|
|
class Permission extends Model
|
|
{
|
|
use NodeTrait, HasRoles, RefreshesPermissionCache;
|
|
|
|
protected $table = 'permissions';
|
|
|
|
protected $fillable = ['id', 'parent_id', 'name', 'title', 'description', 'path', 'icon', 'type', 'status', 'open','height','width', 'displayorder'];
|
|
|
|
/**
|
|
* Get the hidden attributes for the model.
|
|
*
|
|
* @return array
|
|
*/
|
|
public function getHidden()
|
|
{
|
|
return [$this->getLftName(), $this->getRgtName()];
|
|
}
|
|
|
|
/**
|
|
* A permission can be applied to roles.
|
|
*/
|
|
public function roles(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Role::class, 'role_has_permissions');
|
|
}
|
|
|
|
/**
|
|
* Find a permission by its name.
|
|
*
|
|
* @param string $name
|
|
*
|
|
* @throws NotExistException
|
|
*
|
|
* @return Permission
|
|
*/
|
|
public static function findByName(string $name): Permission
|
|
{
|
|
$permission = static::getPermissions()->filter(function ($permission) use ($name) {
|
|
return $permission->name === $name;
|
|
})->first();
|
|
|
|
if (!$permission) {
|
|
throw new NotExistException('权限不存在');
|
|
}
|
|
|
|
return $permission;
|
|
}
|
|
|
|
|
|
/**
|
|
* Find a permission by its id.
|
|
*
|
|
* @param int $id
|
|
*
|
|
* @throws NotExistException
|
|
*
|
|
* @return Permission
|
|
*/
|
|
public static function findById(int $id): Permission
|
|
{
|
|
$permission = static::getPermissions()->filter(function ($permission) use ($id) {
|
|
return $permission->id === $id;
|
|
})->first();
|
|
|
|
if (! $permission) {
|
|
throw new NotExistException('权限不存在');
|
|
}
|
|
|
|
return $permission;
|
|
}
|
|
|
|
/**
|
|
* Get the current cached permissions.
|
|
*/
|
|
protected static function getPermissions(): Collection
|
|
{
|
|
return app(PermissionService::class)->getPermissions();
|
|
}
|
|
}
|