Просмотр файла app/Models/Flood.php

Размер файла: 2.27Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Models;
  6.  
  7. /**
  8. * Class Flood
  9. *
  10. * @property int id
  11. * @property int user_id
  12. * @property string page
  13. * @property int created_at
  14. */
  15. class Flood extends BaseModel
  16. {
  17. /**
  18. * Indicates if the model should be timestamped.
  19. *
  20. * @var bool
  21. */
  22. public $timestamps = false;
  23.  
  24. /**
  25. * The attributes that aren't mass assignable.
  26. *
  27. * @var array
  28. */
  29. protected $guarded = [];
  30.  
  31. /**
  32. * Определяет время антифлуда
  33. *
  34. * @return int
  35. */
  36. public function getPeriod(): int
  37. {
  38. if (isAdmin()) {
  39. return 0;
  40. }
  41.  
  42. $userPoint = getUser('point');
  43. $period = setting('floodstime');
  44.  
  45. if ($userPoint >= 100) {
  46. $period = round(setting('floodstime') / 2);
  47. }
  48.  
  49. if ($userPoint >= 300) {
  50. $period = round(setting('floodstime') / 3);
  51. }
  52.  
  53. if ($userPoint >= 500) {
  54. $period = round(setting('floodstime') / 6);
  55. }
  56.  
  57. return (int) $period;
  58. }
  59.  
  60. /**
  61. * Проверяет сообщение на флуд
  62. *
  63. * @param int $attempts кол. попыток
  64. *
  65. * @return bool
  66. */
  67. public function isFlood(int $attempts = 1): bool
  68. {
  69. self::query()->where('created_at', '<', SITETIME)->delete();
  70.  
  71. $flood = self::query()
  72. ->where('uid', $this->getUid())
  73. ->where('page', request()->getPathInfo())
  74. ->first();
  75.  
  76. if ($flood && $flood->attempts >= $attempts) {
  77. return true;
  78. }
  79.  
  80. return false;
  81. }
  82.  
  83. /**
  84. * Сохраняет состояние
  85. *
  86. * @param int $period
  87. * @return void
  88. */
  89. public function saveState(int $period = 0): void
  90. {
  91. $period = $period ?: $this->getPeriod();
  92.  
  93. if (empty($period)) {
  94. return;
  95. }
  96.  
  97. self::query()->updateOrCreate([
  98. 'uid' => $this->getUid(),
  99. 'page' => request()->getPathInfo(),
  100. ], [
  101. 'created_at' => SITETIME + $period,
  102. ])->increment('attempts');
  103. }
  104.  
  105. /**
  106. * Get uid
  107. *
  108. * @return string
  109. */
  110. private function getUid(): string
  111. {
  112. return md5((string) (getUser('id') ?? getIp()));
  113. }
  114. }