AdminInfo.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace app\admin\controller\routine;
  3. use app\admin\model\Depart;
  4. use app\admin\model\Institution;
  5. use Throwable;
  6. use app\admin\model\Admin;
  7. use app\common\controller\Backend;
  8. class AdminInfo extends Backend
  9. {
  10. /**
  11. * @var object
  12. * @phpstan-var Admin
  13. */
  14. protected object $model;
  15. protected string|array $preExcludeFields = ['username', 'last_login_time', 'password', 'salt', 'status'];
  16. protected array $authAllowFields = ['id', 'username', 'nickname', 'avatar', 'email', 'mobile', 'motto', 'last_login_time','depart','depart_id','institution','institution_id'];
  17. public function initialize(): void
  18. {
  19. parent::initialize();
  20. $this->auth->setAllowFields($this->authAllowFields);
  21. $this->model = $this->auth->getAdmin();
  22. }
  23. public function index(): void
  24. {
  25. $info = $this->auth->getInfo();
  26. $this->success('', [
  27. 'info' => $info
  28. ]);
  29. }
  30. public function edit($id = null): void
  31. {
  32. $row = $this->model->find($id);
  33. if (!$row) {
  34. $this->error(__('Record not found'));
  35. }
  36. if ($this->request->isPost()) {
  37. $data = $this->request->post();
  38. if (!$data) {
  39. $this->error(__('Parameter %s can not be empty', ['']));
  40. }
  41. if (isset($data['avatar']) && $data['avatar']) {
  42. $row->avatar = $data['avatar'];
  43. if ($row->save()) {
  44. $this->success(__('Avatar modified successfully!'));
  45. }
  46. }
  47. // 数据验证
  48. if ($this->modelValidate) {
  49. try {
  50. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  51. $validate = new $validate();
  52. $validate->scene('info')->check($data);
  53. } catch (Throwable $e) {
  54. $this->error($e->getMessage());
  55. }
  56. }
  57. if (isset($data['password']) && $data['password']) {
  58. $this->model->resetPassword($this->auth->id, $data['password']);
  59. }
  60. if (isset($data['institution_id']) && $data['institution_id']) {
  61. $data['institution'] = Institution::where('id',$data['institution_id'])->value('name');
  62. }
  63. if (isset($data['depart_id']) && $data['depart_id']) {
  64. $data['depart'] = Depart::where('id',$data['depart_id'])->value('depart_name');
  65. }
  66. $data = $this->excludeFields($data);
  67. $result = false;
  68. $this->model->startTrans();
  69. try {
  70. $result = $row->save($data);
  71. $this->model->commit();
  72. } catch (Throwable $e) {
  73. $this->model->rollback();
  74. $this->error($e->getMessage());
  75. }
  76. if ($result !== false) {
  77. $this->success(__('Update successful'));
  78. } else {
  79. $this->error(__('No rows updated'));
  80. }
  81. }
  82. }
  83. }