UserTrait.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Modules\User\Http\Controllers;
  3. use Illuminate\Support\Collection;
  4. use Illuminate\Support\Facades\DB;
  5. use Modules\Common\Errors\Errors;
  6. use Modules\Common\Exceptions\CommonBusinessException;
  7. use Modules\User\Models\User;
  8. trait UserTrait
  9. {
  10. // 当前登录用户
  11. protected $currentUser;
  12. /**
  13. * 获取当前登录用户
  14. * @return User
  15. */
  16. protected function getCurrentUser(): User {
  17. if(!$this->currentUser) {
  18. $this->currentUser = $this->getLoginUser();
  19. }
  20. return $this->currentUser;
  21. }
  22. /**
  23. * 当前用户的所有的角色标识的结合
  24. * @return Collection
  25. */
  26. protected function listUserRoles():Collection {
  27. return $this->getCurrentUser()->roles->pluck('identify');
  28. }
  29. /**
  30. * 当前用户是否是cp角色
  31. * @return bool
  32. */
  33. public function userIsCp():bool {
  34. return $this->listUserRoles()->contains('cp');
  35. }
  36. /**
  37. * 如果当前用户是cp角色,返回cp_name,否则返回null
  38. * @return string
  39. */
  40. public function getUserCpName():string|null {
  41. if($this->userIsCp()) {
  42. return DB::table('user_belong_to_cp')
  43. ->where([
  44. 'is_enabled' => 1,
  45. 'user_id' => $this->getCurrentUser()->id,
  46. ])->value('cp_name');
  47. } else {
  48. return null;
  49. }
  50. }
  51. protected function getUserContext($operateUserId) {
  52. $loginUser = $this->getLoginUser();
  53. $loginUserRoles = $this->listUserRoles();
  54. if($operateUserId) {
  55. $operateUser = User::find($operateUserId);
  56. $operateUserRoles = $operateUser->roles->pluck('identify');
  57. if($loginUser->id != $operateUser->pid) {
  58. CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
  59. }
  60. if(!$operateUserRoles->contains('optimizer')) {
  61. CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
  62. }
  63. } else {
  64. $operateUser = $loginUser;
  65. $operateUserRoles = $loginUserRoles;
  66. }
  67. return compact('loginUser', 'loginUserRoles', 'operateUserRoles', 'operateUser');
  68. }
  69. /**
  70. * 获取优化师用户uid
  71. * @return int|null
  72. */
  73. public function getOptimizerUid() {
  74. if($this->isOptimizer()) {
  75. return $this->getCurrentUser()->id;
  76. }
  77. return null;
  78. }
  79. /**
  80. * 是否是优化师
  81. * @return bool
  82. */
  83. public function isOptimizer() {
  84. return $this->listUserRoles()->contains('optimizer');
  85. }
  86. }