ActionLogBehavior.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace common\behaviors;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\web\Controller;
  6. use common\enums\RedisKeyEnum;
  7. use common\enums\MethodEnum;
  8. use common\helpers\DebrisHelper;
  9. use common\models\common\ActionBehavior;
  10. /**
  11. * Class ActionLogBehavior
  12. * @package common\behaviors
  13. * @author qimall
  14. */
  15. class ActionLogBehavior extends Behavior
  16. {
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function events()
  21. {
  22. return [
  23. Controller::EVENT_BEFORE_ACTION => 'beforeAction',
  24. Controller::EVENT_AFTER_ACTION => 'afterAction',
  25. ];
  26. }
  27. /**
  28. * @param $event
  29. * @throws \yii\base\InvalidConfigException
  30. */
  31. public function beforeAction($event)
  32. {
  33. $this->record(ActionBehavior::ACTION_BEFORE, $event);
  34. }
  35. /**
  36. * @param $event
  37. * @throws \yii\base\InvalidConfigException
  38. */
  39. public function afterAction($event)
  40. {
  41. $this->record(ActionBehavior::ACTION_AFTER, $event);
  42. }
  43. /**
  44. * @param $action
  45. * @param $event
  46. * @throws \yii\base\InvalidConfigException
  47. */
  48. public function record($action, $event)
  49. {
  50. $url = DebrisHelper::getUrl();
  51. $nowKey = [];
  52. $nowKey[] = Yii::$app->id;
  53. $nowKey[] = $url;
  54. $nowKey[] = $action;
  55. $nowKey = implode('|', $nowKey);
  56. $data = $this->getActionBehavior();
  57. if (isset($data[$nowKey])) {
  58. $row = $data[$nowKey];
  59. if ($row['method'] != MethodEnum::ALL && Yii::$app->request->method != $row['method']) {
  60. return;
  61. }
  62. if ($row['is_ajax'] != ActionBehavior::AJAX_ALL && Yii::$app->request->isAjax != $row['is_ajax']) {
  63. return;
  64. }
  65. // 记录行为
  66. Yii::$app->services->actionLog->create($row['behavior'], $row['remark'], !empty($row['is_record_post']), $url, $row['level']);
  67. }
  68. }
  69. /**
  70. * @return array|mixed
  71. */
  72. protected function getActionBehavior()
  73. {
  74. $key = RedisKeyEnum::suffix('actionBehavior');
  75. if (!($data = Yii::$app->cache->get($key))) {
  76. $data = Yii::$app->services->actionBehavior->getAllData();
  77. Yii::$app->cache->set($key, $data, 60 * 60 * 2);
  78. }
  79. return $data;
  80. }
  81. }