UserObserver.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace app\backend\modules\user\observers;
  3. use app\backend\modules\user\services\PermissionService;
  4. use app\common\exceptions\ShopException;
  5. use app\common\models\user\UniAccountUser;
  6. use app\common\models\user\UserProfile;
  7. use app\common\models\user\YzPermission;
  8. use app\common\models\user\YzUserRole;
  9. use app\common\observers\BaseObserver;
  10. use Illuminate\Database\Eloquent\Model;
  11. class UserObserver extends BaseObserver
  12. {
  13. public function created(Model $model)
  14. {
  15. //框架操作员属性写入,只有创建后才会写入,商城不支持修改
  16. $uniAccountUserModel = new UniAccountUser();
  17. $accountData = array(
  18. 'uid' => $model->uid,
  19. 'role' => 'operator',
  20. 'rank' => '0',
  21. 'uniacid' => \YunShop::app()->uniacid
  22. );
  23. $uniAccountUserModel->fill($accountData);
  24. if (!$uniAccountUserModel->save()) {
  25. throw new ShopException('操作员user写入失败,请重试!');
  26. }
  27. }
  28. public function deleted(Model $model)
  29. {
  30. YzUserRole::where('user_id', $model->uid)->delete();
  31. }
  32. public function saving(Model $model)
  33. {
  34. //验证操作员简介数据
  35. $profileModel = UserProfile::getProfileByUid($model->uid) ?: new UserProfile();
  36. $profileModel->setRawAttributes($model->widgets['profile']);
  37. $validator = $profileModel->validator();
  38. if ($validator->fails()) {
  39. throw new ShopException($validator->errors()->first());
  40. }
  41. }
  42. public function saved(Model $model)
  43. {
  44. //操作员简介写入 或 修改操作员简介
  45. $profileModel = UserProfile::getProfileByUid($model->uid) ?: new UserProfile();
  46. $profileModel->fill($model->widgets['profile']);
  47. $profileModel->uid = $model->uid;
  48. if (config('app.framework') != 'platform') {
  49. $profileModel->createtime = time();
  50. }
  51. if (!$profileModel->save()) {
  52. throw new ShopException('操作员简介写入失败,请重试!!');
  53. }
  54. //操作员角色写入 或 修改 没有主键的表,删除原数据重新添加
  55. YzUserRole::removeDataByUserId($model->uid);
  56. $yzUserRoleModel = new YzUserRole();
  57. $yzUserRoleModel->user_id = $model->uid;
  58. $yzUserRoleModel->role_id = $model->widgets['role_id'] ?: '0';
  59. if (!$yzUserRoleModel->save()) {
  60. throw new ShopException('操作员角色关联写入失败,请重试!!');
  61. }
  62. //操作员权限写入 或 修改, 修改时需注意:挂件中的 permission 需要去除角色权限
  63. //同时,目前采用删除操作员原权限,写入新权限做法
  64. YzPermission::deleteUserPermissionByUserId($model->uid);
  65. if ($model->widgets['perms']) {
  66. $permissions = (new PermissionService())->addedToPermission($model->widgets['perms'], YzPermission::TYPE_USER, $model->uid);
  67. if (!YzPermission::insertYzPermission($permissions)) {
  68. throw new ShopException('写入操作员权限失败,请重新编辑!!');
  69. }
  70. }
  71. }
  72. }