AdminInfo.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace app\admin\controller\routine;
  3. use Throwable;
  4. use app\admin\model\Admin;
  5. use app\common\controller\Backend;
  6. class AdminInfo extends Backend
  7. {
  8. /**
  9. * @var object
  10. * @phpstan-var Admin
  11. */
  12. protected object $model;
  13. protected string|array $preExcludeFields = ['username', 'last_login_time', 'password', 'salt', 'status'];
  14. protected array $authAllowFields = ['id', 'username', 'nickname', 'avatar', 'email', 'mobile', 'motto', 'last_login_time'];
  15. public function initialize(): void
  16. {
  17. parent::initialize();
  18. $this->auth->setAllowFields($this->authAllowFields);
  19. $this->model = $this->auth->getAdmin();
  20. }
  21. public function index(): void
  22. {
  23. $info = $this->auth->getInfo();
  24. $this->success('', [
  25. 'info' => $info
  26. ]);
  27. }
  28. public function edit(): void
  29. {
  30. $pk = $this->model->getPk();
  31. $id = $this->request->param($pk);
  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 (!empty($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 (!empty($data['password'])) {
  58. $this->model->resetPassword($this->auth->id, $data['password']);
  59. }
  60. $data = $this->excludeFields($data);
  61. $result = false;
  62. $this->model->startTrans();
  63. try {
  64. $result = $row->save($data);
  65. $this->model->commit();
  66. } catch (Throwable $e) {
  67. $this->model->rollback();
  68. $this->error($e->getMessage());
  69. }
  70. if ($result !== false) {
  71. $this->success(__('Update successful'));
  72. } else {
  73. $this->error(__('No rows updated'));
  74. }
  75. }
  76. }
  77. }