| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- <?php
- namespace App\Http\Middleware;
- /*
- * TrackPageVisit — считает публичные просмотры страниц.
- * Обновляет/создаёт строку в page_visits за текущую дату.
- * Уникальные IP считаются через Rate Limiter — один IP раз в сутки.
- * Исключает запросы к /admin, /api, статику.
- */
- use Closure;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- use Symfony\Component\HttpFoundation\Response;
- class TrackPageVisit
- {
- public function handle(Request $request, Closure $next): Response
- {
- $response = $next($request);
- // Только GET-запросы на публичные HTML-страницы
- if (
- $request->isMethod('GET')
- && !$request->is('admin/*', 'admin')
- && !$request->ajax()
- && !$request->expectsJson()
- && str_contains($response->headers->get('Content-Type', ''), 'text/html')
- ) {
- $today = now()->toDateString();
- $ip = $request->ip();
- $isNew = Cache::add("visit_ip_{$today}_{$ip}", 1, now()->endOfDay());
- DB::table('page_visits')
- ->upsert(
- ['date' => $today, 'views' => 1, 'unique_ips' => $isNew ? 1 : 0],
- ['date'],
- ['views' => DB::raw('views + 1'), 'unique_ips' => DB::raw('unique_ips + ' . ($isNew ? 1 : 0))]
- );
- }
- return $response;
- }
- }
|