TrackPageVisit.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Http\Middleware;
  3. /*
  4. * TrackPageVisit — считает публичные просмотры страниц.
  5. * Обновляет/создаёт строку в page_visits за текущую дату.
  6. * Уникальные IP считаются через Rate Limiter — один IP раз в сутки.
  7. * Исключает запросы к /admin, /api, статику.
  8. */
  9. use Closure;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Facades\Cache;
  12. use Illuminate\Support\Facades\DB;
  13. use Symfony\Component\HttpFoundation\Response;
  14. class TrackPageVisit
  15. {
  16. public function handle(Request $request, Closure $next): Response
  17. {
  18. $response = $next($request);
  19. // Только GET-запросы на публичные HTML-страницы
  20. if (
  21. $request->isMethod('GET')
  22. && !$request->is('admin/*', 'admin')
  23. && !$request->ajax()
  24. && !$request->expectsJson()
  25. && str_contains($response->headers->get('Content-Type', ''), 'text/html')
  26. ) {
  27. $today = now()->toDateString();
  28. $ip = $request->ip();
  29. $isNew = Cache::add("visit_ip_{$today}_{$ip}", 1, now()->endOfDay());
  30. DB::table('page_visits')
  31. ->upsert(
  32. ['date' => $today, 'views' => 1, 'unique_ips' => $isNew ? 1 : 0],
  33. ['date'],
  34. ['views' => DB::raw('views + 1'), 'unique_ips' => DB::raw('unique_ips + ' . ($isNew ? 1 : 0))]
  35. );
  36. }
  37. return $response;
  38. }
  39. }