FactoryContext.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace app\common\library\ps;
  3. use app\common\library\Auth as FrontendAuth;
  4. use think\Request;
  5. /**
  6. * 当前请求的工厂上下文。超管后台默认不注入工厂条件。
  7. */
  8. class FactoryContext
  9. {
  10. /**
  11. * 是否跳过工厂隔离(超管后台)
  12. * @return bool
  13. */
  14. public static function bypass()
  15. {
  16. if (defined('IS_CLI') && IS_CLI) {
  17. return true;
  18. }
  19. $module = Request::instance()->module();
  20. return $module === 'admin';
  21. }
  22. protected static $forcedId = 0;
  23. /**
  24. * Open API 绑定当前工厂(无会员登录)
  25. * @param int $factoryId
  26. */
  27. public static function bindFactory($factoryId)
  28. {
  29. self::$forcedId = (int)$factoryId;
  30. }
  31. /**
  32. * 当前会员所属工厂 ID
  33. * @return int
  34. */
  35. public static function id()
  36. {
  37. if (self::$forcedId > 0) {
  38. return self::$forcedId;
  39. }
  40. $auth = FrontendAuth::instance();
  41. if (!$auth || !$auth->isLogin()) {
  42. return 0;
  43. }
  44. return (int)$auth->factory_id;
  45. }
  46. /**
  47. * 当前操作员会员 ID
  48. * @return int
  49. */
  50. public static function userId()
  51. {
  52. $auth = FrontendAuth::instance();
  53. if (!$auth || !$auth->isLogin()) {
  54. return 0;
  55. }
  56. return (int)$auth->id;
  57. }
  58. /**
  59. * 是否工厂管理员
  60. * @return bool
  61. */
  62. public static function isOwner()
  63. {
  64. $auth = FrontendAuth::instance();
  65. return $auth && $auth->isLogin() && $auth->factory_role === 'owner';
  66. }
  67. /**
  68. * Open API 已按 Key 绑定工厂(无会员登录)
  69. * @return bool
  70. */
  71. public static function isApiBound()
  72. {
  73. return self::$forcedId > 0;
  74. }
  75. /**
  76. * 未入厂则抛业务异常给 API 基类处理
  77. * @return int
  78. */
  79. public static function requireId()
  80. {
  81. $id = self::id();
  82. if ($id <= 0 && !self::bypass()) {
  83. throw new \think\Exception('账号未绑定工厂');
  84. }
  85. return $id;
  86. }
  87. }