DepartmentScope.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. $is_all_depart = $this->user['is_all_depart'] ?? 0;
  21. //权限范围内的部门
  22. $depart_range = $this->user['depart_range'] ?? [];
  23. //我可见的
  24. $is_see = $this->search['is_see'] ?? 0;
  25. //可见范围方法
  26. $range_function = $this->user['range_function'] ?? "";
  27. $is_function_range = $this->hasMethod(new RangeService(),$range_function);
  28. //顶级部门
  29. $search_depart_id = $this->search['top_depart_id'] ?? 0; //顶级公司
  30. if(empty($search_depart_id)){
  31. //默认进来 自身顶级公司
  32. $top_depart_id = $this->user['depart_top'][0] ?? [];
  33. $top_depart_id = $top_depart_id['depart_id'] ?? 0;
  34. }else{
  35. //查询 顶级公司
  36. $top_depart_id = $search_depart_id;
  37. }
  38. $id = [];
  39. //可见范围 以及单据里面填写人员
  40. if($is_function_range) $id = RangeService::$range_function($this->user,$this->search);
  41. if($is_all_depart){
  42. //所有部门
  43. if(empty($search_depart_id)){
  44. if(! $is_see){
  45. //全部
  46. $builder->whereIn('depart_id', $depart_range);
  47. }else{
  48. //可见
  49. $builder->whereIn('id', $id);
  50. }
  51. }else{
  52. if(! $is_see){
  53. //查看某个分社
  54. $builder->where('top_depart_id', $top_depart_id);
  55. }else{
  56. //查看某个分社可见
  57. $builder->whereIn('id', $id);
  58. }
  59. }
  60. }else{
  61. //分社
  62. if(! $is_see){
  63. //某个分社全部
  64. $builder->where('top_depart_id', $top_depart_id)
  65. ->whereIn('depart_id', $depart_range)
  66. ->orWhereIn('id', $id);
  67. }else{
  68. //某个分社可见
  69. $builder->whereIn('id', $id);
  70. }
  71. }
  72. }
  73. function hasMethod($class, $methodName)
  74. {
  75. $reflection = new \ReflectionClass($class);
  76. return $reflection->hasMethod($methodName);
  77. }
  78. }