File size: 2,397 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace App\Http\Middleware;

use App\Models\UserOpenai;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class ViewSharedMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check()) {

            if (
                ! Cache::has('total_words_' . Auth::id())
                or ! Cache::has('total_documents_' . Auth::id())
                or ! Cache::has('total_text_documents_' . Auth::id())
                or ! Cache::has('total_image_documents_' . Auth::id())
            ) {
                $total_documents_finder = UserOpenai::where('user_id', Auth::id())->get();
                $total_words = UserOpenai::where('user_id', Auth::id())->sum('credits');
                Cache::put('total_words_' . Auth::id(), $total_words, now()->addMinutes(360));
                $total_documents = count($total_documents_finder);
                Cache::put('total_documents_' . Auth::id(), $total_documents, now()->addMinutes(360));
                $total_text_documents = count($total_documents_finder->where('credits', '!=', 1));
                Cache::put('total_text_documents_' . Auth::id(), $total_text_documents, now()->addMinutes(360));
                $total_image_documents = count($total_documents_finder->where('credits', '==', 1));
                Cache::put('total_image_documents_' . Auth::id(), $total_image_documents, now()->addMinutes(360));
            }
            $total_words = Cache::get('total_words_' . Auth::id()) ?? 0;
            View::share('total_words', $total_words);
            $total_documents = Cache::get('total_documents_' . Auth::id()) ?? 0;
            View::share('total_documents', $total_documents);
            $total_text_documents = Cache::get('total_text_documents_' . Auth::id()) ?? 0;
            View::share('total_text_documents', $total_text_documents);
            $total_image_documents = Cache::get('total_image_documents_' . Auth::id()) ?? 0;
            View::share('total_image_documents', $total_image_documents);
        }

        return $next($request);
    }
}