123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- namespace App\Traits;
- use App\Http\Resources\AdminPermissionResource;
- use App\Http\Resources\AdminRoleResource;
- use App\Http\Resources\AreaResource;
- use App\Models\AdminUser;
- use App\Models\Area;
- use Illuminate\Support\Str;
- trait ResourceRolePermissionHelpers
- {
- /**
- * 关联的角色和权限, 是否只是 id 数组
- *
- * @var bool
- */
- protected $onlyRolePermissionIds = false;
- /**
- * 关联的角色和权限,只包含 slug
- *
- * @var bool
- */
- protected $onlyRolePermissionSlugs = false;
- /**
- * 获取所有权限,包括角色中的
- *
- * @var bool
- */
- protected $gatherAllPermissions = false;
- protected $onlyAreasIds = false;
- public function onlyRolePermissionIds($yes = true)
- {
- $this->onlyRolePermissionIds = $yes;
- $this->onlyAreasIds = $yes;
- return $this;
- }
- public function onlyRolePermissionSlugs($yes = true)
- {
- $this->onlyRolePermissionSlugs = $yes;
- return $this;
- }
- public function gatherAllPermissions($yes = true)
- {
- $this->gatherAllPermissions = $yes;
- return $this;
- }
- protected function getRoles()
- {
- /** @var AdminUser $model */
- $model = $this->resource;
- if ($this->onlyRolePermissionIds) {
- return $model->roles()->pluck('id');
- } elseif ($this->onlyRolePermissionSlugs) {
- return $model->roles()->pluck('slug');
- } else {
- return AdminRoleResource::collection($this->whenLoaded('roles'));
- }
- }
- protected function getAreas()
- {
- /** @var AdminUser $model */
- $model = $this->resource;
- if($this->onlyAreasIds) {
- return $model->areas()->pluck('areas.id');
- }
- return AreaResource::collection($this->whenLoaded('areas'));
- }
- protected function getPermissions()
- {
- /** @var AdminUser $model */
- $model = $this->resource;
- if ($this->gatherAllPermissions) {
- $perms = $model->allPermissions();
- } else {
- $perms = $model->permissions();
- }
- if ($this->onlyRolePermissionIds) {
- return $perms->pluck('id');
- } elseif ($this->onlyRolePermissionSlugs) {
- return $perms->pluck('slug');
- } elseif ($this->gatherAllPermissions) {
- return AdminPermissionResource::collection($perms);
- } else {
- return AdminPermissionResource::collection($this->whenLoaded('permissions'));
- }
- }
- }
|