AuthRole.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace common\models\rbac;
  3. use common\enums\AppEnum;
  4. use common\enums\StatusEnum;
  5. use common\helpers\ArrayHelper;
  6. use PHPUnit\Util\Exception;
  7. use Yii;
  8. use common\traits\Tree;
  9. use yii\behaviors\TimestampBehavior;
  10. use yii\db\ActiveRecord;
  11. /**
  12. * This is the model class for table "rf_rbac_auth_role".
  13. *
  14. *
  15. * @property int $id 主键
  16. * @property int $merchant_id 商户id
  17. * @property string $title 标题
  18. * @property string $app_id 应用
  19. * @property int $pid 上级id
  20. * @property int $level 级别
  21. * @property int $sort 排序
  22. * @property string $tree 树
  23. * @property int $is_default 是否默认角色
  24. * @property int $status 状态[-1:删除;0:禁用;1启用]
  25. * @property int $created_at 添加时间
  26. * @property int $updated_at 修改时间
  27. * @property int $mall_id 商城id
  28. */
  29. class AuthRole extends \common\models\base\BaseActiveRecord
  30. {
  31. const STATUS_ARR = ['-1' => '删除', '0' => '禁用', '1' => '启用'];
  32. use Tree;
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public static function tableName()
  37. {
  38. return '{{%rbac_auth_role}}';
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function rules()
  44. {
  45. return [
  46. [['title'], 'trim'],
  47. [['title', 'pid'], 'required'],
  48. [['title'], 'isUniquTitle'],
  49. [['merchant_id', 'pid', 'mall_id', 'is_default', 'level', 'sort', 'status', 'created_at', 'updated_at'], 'integer'],
  50. [['title'], 'string', 'max' => 50],
  51. [['app_id'], 'string', 'max' => 20],
  52. [['tree'], 'string', 'max' => 300],
  53. ];
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function attributeLabels()
  59. {
  60. return [
  61. 'id' => '主键',
  62. 'merchant_id' => '商户id',
  63. 'title' => '标题',
  64. 'app_id' => '应用',
  65. 'pid' => '上级角色',
  66. 'level' => '级别',
  67. 'sort' => '排序',
  68. 'tree' => '树',
  69. 'is_default' => '默认',
  70. 'status' => '状态',
  71. 'created_at' => '添加时间',
  72. 'updated_at' => '修改时间',
  73. 'mall_id' => '商城id',
  74. ];
  75. }
  76. /**
  77. * @param $attribute
  78. */
  79. public function isUniquTitle($attribute)
  80. {
  81. $merchant_id = $this->merchant_id;
  82. $mall_id = $this->mall_id;
  83. $model = self::find()->where([
  84. 'merchant_id' => $merchant_id,
  85. 'mall_id' => $mall_id,
  86. 'title' => $this->title,
  87. 'status'=>[StatusEnum::ENABLED,StatusEnum::DISABLED]
  88. ])->one();
  89. if ($model && $model->id != $this->id) {
  90. $this->addError($attribute, '角色名称已存在');
  91. }
  92. }
  93. /**
  94. * 关联模型
  95. * @return \yii\db\ActiveQuery
  96. */
  97. public function getChild()
  98. {
  99. return $this->hasMany(self::class, ['pid' => 'id'])->where(['<>', 'status', StatusEnum::DELETE])->orderBy('sort asc,id asc');
  100. }
  101. /**
  102. * @param array $cond
  103. * @param array $with
  104. * @param int $is_array
  105. * @return array|AuthRole[]|ActiveRecord[]\
  106. */
  107. public static function getRole(array $cond = [], array $with = [], bool $is_array = true)
  108. {
  109. $query = self::find();
  110. self::paramPack(['where' => $cond, 'with' => $with], $query);
  111. return $query->asArray($is_array)->orderBy('sort asc,id desc')->all();
  112. }
  113. public static function getDropDownForEdit($app_id,$mall_id='', $id = '')
  114. {
  115. $list = AuthRole::find()->where(['app_id' => $app_id,'mall_id'=>$mall_id,'status'=>StatusEnum::ENABLED])->asArray()->all();
  116. $list = ArrayHelper::removeByValue($list, $id);
  117. $models = ArrayHelper::itemsMerge($list);
  118. $data = ArrayHelper::map(ArrayHelper::itemsMergeDropDown($models), 'id', 'title');
  119. // if (\Yii::$app->services->rbacAuthRole->isSuperAdmin()) {
  120. return ArrayHelper::merge([0 => '顶级角色'], $data);
  121. // }
  122. return $data;
  123. }
  124. public static function getEditData($params)
  125. {
  126. $where = ['and',
  127. ['id' => $params['id']],
  128. ['mall_id' => $params['mall_id']],
  129. ['status'=> [StatusEnum::ENABLED,StatusEnum::DISABLED]],
  130. ];
  131. $query = AuthRole::find()->where($where);
  132. $role = $query->asArray()->one();
  133. $data['role'] = !empty($role) ? $role : [];
  134. $data['checked_key'] = AuthItemChild::getCheckedKey(['role_id' => $params['id']]);
  135. $list = AuthRole::getDropDownForEdit($params['app_id'],$params['mall_id']);
  136. $data['list'] = $list;
  137. $parent_title = '顶级角色';
  138. if (!empty($items['pid'])) {
  139. $parent_item = AuthRole::getOne([['id' => $items['pid']],['<>', 'status', StatusEnum::DELETE]],true);
  140. $parent_title = $parent_item['title'];
  141. }
  142. $data['parent_title'] = $parent_title;
  143. return $data;
  144. }
  145. /**
  146. * 更新
  147. * @param $params
  148. * @return bool
  149. */
  150. public static function updateRole($params)
  151. {
  152. try {
  153. $query = AuthRole::find()->where(['and',
  154. ['id' => $params['id']],
  155. ['mall_id' => empty($params['mall_id']) ? 0 : $params['mall_id']],
  156. ['in', 'status', [StatusEnum::ENABLED, StatusEnum::DISABLED]],
  157. ]);
  158. $model = $query->one();
  159. isset($params['sort']) && $model->sort = $params['sort'];
  160. isset($params['status']) && $model->status = $params['status'];
  161. return $model->save();
  162. } catch (\Exception $e) {
  163. return false;
  164. }
  165. }
  166. /**
  167. * 保存数据
  168. * @param array $params
  169. * @return bool|AuthRole
  170. * @throws \yii\db\Exception
  171. */
  172. public static function setData(array $params)
  173. {
  174. $t = \Yii::$app->db->beginTransaction();
  175. try {
  176. if (!empty($id = $params['id']) && !empty($pid = $params['pid'])) {
  177. if (static::isChildIdOrSelf($id, $pid)) throw new Exception('上级角色无法选择自己或者其下级角色');
  178. }
  179. if (!empty($params['id'])) {
  180. $where = ['id' => $params['id'], ['status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]];
  181. if (isset($params['mall_id'])) $where[] = ['mall_id' => $params['mall_id']];
  182. $model = self::findOne($where);
  183. if (empty($model)) {
  184. $t->rollBack();
  185. throw new Exception('服务不存在或已删除');
  186. }
  187. } else {
  188. $model = new self();
  189. $model->loadDefaultValues();
  190. }
  191. isset($params['merchant_id']) && $model->merchant_id = $params['merchant_id'];
  192. isset($params['title']) && $model->title = $params['title'];
  193. isset($params['app_id']) && $model->app_id = $params['app_id'];
  194. isset($params['pid']) && $model->pid = $params['pid'];
  195. isset($params['sort']) && $model->sort = $params['sort'];
  196. isset($params['is_default']) && $model->is_default = $params['is_default'];
  197. isset($params['status']) && $model->status = $params['status'];
  198. isset($params['mall_id']) && $model->mall_id = $params['mall_id'];
  199. $model->level = 1;
  200. $model->tree = 'tr_0';
  201. if (!empty($model->pid)) {
  202. $rbac_item = AuthItem::findOne($model->pid);
  203. $model->level = ($rbac_item->level ?? 0) + 1;
  204. $model->tree = ($rbac_item->tree ?? '') . ' tr_' . ($rbac_item['id'] ?? '');
  205. }
  206. $res = $model->save();
  207. if ($res === false) {
  208. $t->rollBack();
  209. throw new Exception($model->getErrorMessage());
  210. }
  211. if (!empty($res) && !empty($params['item_ids'])) {
  212. AuthItemChild::deleteAll(['role_id' => $params['id']]);
  213. $auth_item_list = AuthItem::find()->where(['and', ['in', 'id', $params['item_ids']], ['<>', 'status', StatusEnum::DELETE]])->indexBy('id')->all();
  214. foreach ($params['item_ids'] as $v) {
  215. $batch_insert_data[] = [
  216. 'role_id' => $model->id,
  217. 'item_id' => $v,
  218. 'app_id' => $params['app_id'],
  219. 'name' => empty($auth_item_list[$v]['name']) ? '' : $auth_item_list[$v]['name'],
  220. 'is_addon' => empty($auth_item_list[$v]['is_addon']) ? 0 : $auth_item_list[$v]['is_addon'],
  221. 'addons_name' => empty($auth_item_list[$v]['addons_name']) ? '' : $auth_item_list[$v]['addons_name'],
  222. ];
  223. }
  224. $res = AuthItemChild::batchInsertAuth($batch_insert_data);
  225. if ($res === false) {
  226. $t->rollBack();
  227. throw new Exception($model->getErrorMessage());
  228. }
  229. }
  230. if (empty($params['item_ids'])) {
  231. AuthItemChild::deleteAll(['role_id' => $params['id']]);
  232. }
  233. $t->commit();
  234. return $model;
  235. } catch (Exception $e) {
  236. $t->rollBack();
  237. self::$static_error = $e->getMessage();
  238. return false;
  239. }
  240. }
  241. /**
  242. * pid是否是id的子节点,或者自己
  243. *
  244. * @param integer $id
  245. * @param integer $pid
  246. * @return boolean
  247. */
  248. public static function isChildIdOrSelf(int $id, int $pid)
  249. {
  250. $ids = [$id];
  251. $tmp_id = $id;
  252. while ($child_ids = static::find()->select('id')->where(['pid' => $tmp_id])->column()) {
  253. $ids = array_merge($child_ids, $ids);
  254. $tmp_id = $child_ids;
  255. }
  256. return in_array($pid, $ids);
  257. }
  258. }