DepartmentScope.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Scopes;
  3. use App\Service\RangeService;
  4. use Illuminate\Database\Eloquent\Builder;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Scope;
  7. //判断所属部门和顶级部门
  8. class DepartmentScope implements Scope
  9. {
  10. public $user = [];
  11. public $search = [];
  12. public function __construct($user = [], $search = [])
  13. {
  14. $this->user = $user;
  15. $this->search = $search;
  16. }
  17. public function apply(Builder $builder, Model $model)
  18. {
  19. //权限范围内的部门
  20. $depart_range = $this->user['depart_range'] ?? [];
  21. //我可见的
  22. $is_see = $this->search['is_see'] ?? 0;
  23. //可见范围方法
  24. $range_function = $this->user['range_function'] ?? "";
  25. $is_function_range = $this->hasMethod(new RangeService(),$range_function);
  26. //顶级部门
  27. $search_depart_id = $this->search['top_depart_id'] ?? 0; //顶级公司
  28. if(empty($search_depart_id)){
  29. //默认进来 自身顶级公司
  30. $top_depart_id = $this->user['depart_top'][0] ?? [];
  31. $top_depart_id = $top_depart_id['depart_id'] ?? 0;
  32. }else{
  33. //查询 顶级公司
  34. $top_depart_id = $search_depart_id;
  35. }
  36. //顶级部门下 权限范围内部门的所有数据
  37. $builder->where('top_depart_id', $top_depart_id)
  38. ->whereIn('depart_id', $depart_range);
  39. //加上可见范围 部门 人以后的数据
  40. $id = [];
  41. if($is_see && $is_function_range) $id = RangeService::$range_function($this->user);
  42. $builder->orWhereIn('id', $id);
  43. if(! empty($this->user['is_search_main'])) $builder->orWhere('is_main', '>',0);
  44. }
  45. function hasMethod($class, $methodName)
  46. {
  47. $reflection = new \ReflectionClass($class);
  48. return $reflection->hasMethod($methodName);
  49. }
  50. }