ActionLog.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\modules\admin\behaviors;
  8. use Yii;
  9. use yii\base\ActionFilter;
  10. use app\models\ActionLog as ActionLogModel;
  11. /**
  12. * 记录操作日志
  13. * Class ActionLog
  14. * @package app\modules\admin\behaviors
  15. */
  16. class ActionLog extends ActionFilter
  17. {
  18. public function beforeAction($action)
  19. {
  20. $params = require Yii::$app->basePath . '/config/action.php';
  21. $route = Yii::$app->controller->route;
  22. Yii::$app->cache->delete('actionLogId');
  23. if (isset($params[$route])) {
  24. $param = $params[$route];
  25. $getParams = get_params();
  26. $postParams = post_params();
  27. $headerParams = Yii::$app->getRequest()->getHeaders()->toArray();
  28. if (isset($postParams['password'])) {
  29. unset($postParams['password']);
  30. }
  31. $dataID = isset($param['key']) ? input_params($param['key']) : null;
  32. $type = isset($param['type']) ? $param['type'] : ($dataID ? 'edit' : 'add');
  33. $admin = Yii::$app->jwt->getAdmin();
  34. $adminId = $admin ? $admin->getId() : null;
  35. $actionLog = new ActionLogModel();
  36. $actionLog->route = $route;
  37. if ($adminId) {
  38. $actionLog->admin_id = $adminId;
  39. }
  40. $actionLog->type = $type;
  41. $actionLog->data_id = is_array($dataID) ? json_encode($dataID) : $dataID;
  42. $actionLog->get_params = $getParams ? json_encode($getParams) : '';
  43. $actionLog->post_params = $postParams ? json_encode($postParams) : '';
  44. $actionLog->header_params = $headerParams ? json_encode($headerParams) : '';
  45. if ($actionLog->save()) {
  46. Yii::$app->cache->set('actionLogId', Yii::$app->db->getLastInsertID());
  47. } else {
  48. Yii::error($actionLog->getErrors());
  49. }
  50. }
  51. return parent::beforeAction($action);
  52. }
  53. public function afterAction($action, $result)
  54. {
  55. $actionLogId = Yii::$app->cache->get('actionLogId');
  56. if ($actionLogId) {
  57. $actionLog = ActionLogModel::findOne($actionLogId);
  58. if ($actionLog) {
  59. $admin = Yii::$app->jwt->getAdmin();
  60. if ($actionLog->type == 'login' && $admin) {
  61. $actionLog->admin_id = $admin->getId();
  62. }
  63. $actionLog->response_params = json_encode($result);
  64. $actionLog->save();
  65. }
  66. }
  67. return parent::afterAction($action, $result);
  68. }
  69. }