catchAdmin/catch/permissions/model/DataRangScopeTrait.php

87 lines
2.2 KiB
PHP
Raw Normal View History

2020-06-06 18:57:58 +08:00
<?php
namespace catchAdmin\permissions\model;
use catcher\Utils;
2020-06-06 18:57:58 +08:00
trait DataRangScopeTrait
{
/**
* 数据范围查询
*
* @param $roles
* @return mixed
* @author JaguarJack <njphper@gmail.com>
* @date 2020/6/6
*/
2020-07-04 21:35:01 +08:00
protected function dataRange($roles)
2020-06-06 18:57:58 +08:00
{
if (Utils::isSuperAdmin()) {
return $this;
}
$userIds = $this->getDepartmentUserIdsBy($roles);
if (empty($userIds)) {
return $this;
}
return $this->whereIn($this->aliasField('creator_id'), $userIds);
2020-06-06 18:57:58 +08:00
}
/**
* 获取部门IDs
*
* @param $roles
* @return array
* @author JaguarJack <njphper@gmail.com>
* @date 2020/6/6
*/
public function getDepartmentUserIdsBy($roles)
{
$userIds = [];
$isAll = false;
$user = request()->user();
foreach ($roles as $role) {
switch ($role->data_range) {
case Roles::ALL_DATA:
$isAll = true;
break;
case Roles::SELF_CHOOSE:
$departmentIds = array_merge(array_column($role->getDepartments()->toArray(), 'id'));
2020-07-04 14:28:59 +08:00
$userIds = array_merge($userIds, $this->getUserIdsByDepartmentId($departmentIds));
2020-06-06 18:57:58 +08:00
break;
case Roles::SELF_DATA:
$userIds[] = $user->id;
break;
case Roles::DEPARTMENT_DOWN_DATA:
case Roles::DEPARTMENT_DATA:
2020-07-04 14:28:59 +08:00
$userIds = array_merge($userIds, $this->getUserIdsByDepartmentId([$user->department_id]));
2020-06-06 18:57:58 +08:00
break;
default:
break;
}
// 如果有全部数据 直接跳出
if ($isAll) {
break;
}
}
return $userIds;
}
2020-07-04 14:28:59 +08:00
/**
* 获取UserID
*
* @time 2020年07月04日
* @param $id
* @return array
*/
protected function getUserIdsByDepartmentId(array $id)
{
return Users::whereIn('department_id', $id)->column('id');
}
2020-06-06 18:57:58 +08:00
}