AdminInfo.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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($id = null): void
  29. {
  30. $row = $this->model->find($id);
  31. if (!$row) {
  32. $this->error(__('Record not found'));
  33. }
  34. if ($this->request->isPost()) {
  35. $data = $this->request->post();
  36. if (!$data) {
  37. $this->error(__('Parameter %s can not be empty', ['']));
  38. }
  39. if (isset($data['avatar']) && $data['avatar']) {
  40. $row->avatar = $data['avatar'];
  41. if ($row->save()) {
  42. $this->success(__('Avatar modified successfully!'));
  43. }
  44. }
  45. // 数据验证
  46. if ($this->modelValidate) {
  47. try {
  48. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  49. $validate = new $validate;
  50. $validate->scene('info')->check($data);
  51. } catch (Throwable $e) {
  52. $this->error($e->getMessage());
  53. }
  54. }
  55. if (isset($data['password']) && $data['password']) {
  56. $this->model->resetPassword($this->auth->id, $data['password']);
  57. }
  58. $data = $this->excludeFields($data);
  59. $result = false;
  60. $this->model->startTrans();
  61. try {
  62. $result = $row->save($data);
  63. $this->model->commit();
  64. } catch (Throwable $e) {
  65. $this->model->rollback();
  66. $this->error($e->getMessage());
  67. }
  68. if ($result !== false) {
  69. $this->success(__('Update successful'));
  70. } else {
  71. $this->error(__('No rows updated'));
  72. }
  73. }
  74. }
  75. }