Procházet zdrojové kódy

日志查询优化搜索条件

ANG YU před 5 roky
rodič
revize
6143fb007b
3 změnil soubory, kde provedl 129 přidání a 58 odebrání
  1. 116 0
      app/Filters/LogFilters.php
  2. 9 58
      app/Http/Controllers/LogController.php
  3. 4 0
      app/Log.php

+ 116 - 0
app/Filters/LogFilters.php

@@ -0,0 +1,116 @@
+<?php
+
+
+namespace App\Filters;
+
+
+use Carbon\Carbon;
+use Illuminate\Http\Request;
+use Illuminate\Support\Arr;
+
+class LogFilters
+{
+    protected $request;
+    protected $queryBuilder;
+    protected $filters = ['username', 'type', 'description',
+        'created_at_start', 'created_at_end', 'is_exception'];
+    protected $array_filter;
+
+    public function __construct(Request $request)
+    {
+        $this->request = $request;
+        $this->array_filter = array_filter($this->request->only($this->filters));
+    }
+
+    public function apply($builder)
+    {
+        $this->queryBuilder = $builder;
+        foreach ($this->array_filter as $filter => $value) {
+            if (method_exists($this, $filter)) {
+                $this->$filter($value, $this->queryBuilder);
+            }
+        }
+        return $this->afterApply($this->queryBuilder);
+    }
+
+    /**
+     * 后置处理,解决查询条件之间的关联关系,方法名后缀’_after‘
+     * @param $builder
+     * @return mixed
+     */
+    public function afterApply($builder)
+    {
+        $this->queryBuilder = $builder;
+        foreach ($this->array_filter as $filter => $value) {
+            $filter .= '_after';
+            if (method_exists($this, $filter)) {
+                $this->$filter($value, $this->queryBuilder);
+            }
+        }
+        if (!Arr::hasAny($this->array_filter, ['created_at_start', 'created_at_end'])) {
+            $start = Carbon::now()->toDateString();
+            $end = Carbon::tomorrow()->toDateString();
+            $this->queryBuilder = $this->queryBuilder->where('created_at', '>=', $start)->where('created_at', '<', $end);
+        }
+        return $this->queryBuilder;
+    }
+
+    private function created_at_start($created_at_start)
+    {
+        $this->queryBuilder->where('created_at', '>=', $created_at_start);
+    }
+
+    private function created_at_end($created_at_end)
+    {
+        $this->queryBuilder->where('created_at', '<', Carbon::parse($created_at_end)->addDay()->toDateString());
+    }
+
+    /**
+     * 如果中传入开始时间,默认结束时间为开始时间的下一天
+     * @param $created_at_start
+     */
+    private function created_at_start_after($created_at_start)
+    {
+        if (!Arr::has($this->array_filter, 'created_at_end')) {
+            $endDay = Carbon::parse($created_at_start)->addDay()->toDateString();
+            $this->queryBuilder->where('created_at', '<', $endDay);
+        }
+    }
+
+    /**
+     * 如果只传入截止时间,只查询截止时间这一天的数据
+     * @param $created_at_end
+     */
+    private function created_at_end_after($created_at_end)
+    {
+        if (!Arr::has($this->array_filter, 'created_at_start')) {
+            $startDay = Carbon::parse($created_at_end)->toDateString();
+            $this->queryBuilder->where('created_at', '>=', $startDay);
+        }
+    }
+
+    private function description($description)
+    {
+        $this->queryBuilder->where("description", 'like', $description . '%');
+    }
+
+    private function type($type)
+    {
+        $types = array_filter(preg_split('/[,, ]+/is', $type));
+        $this->queryBuilder->whereIn("type", $types);
+    }
+
+    private function username($username)
+    {
+        $this->queryBuilder->whereIn("id_user", function ($query) use ($username) {
+            return $query->from("users")->select("id")->where("name", 'like', $username . '%');
+        });
+    }
+
+    private function is_exception()
+    {
+        $this->queryBuilder->where(function ($query) {
+            $query->where("method", "like", "ERROR%")->orWhere("method", "like", "EXCEPTION%");
+        });
+    }
+}

+ 9 - 58
app/Http/Controllers/LogController.php

@@ -2,87 +2,38 @@
 
 namespace App\Http\Controllers;
 
+use App\Filters\LogFilters;
 use App\Log;
 use App\Services\LogService;
-use Exception;
 use Illuminate\Contracts\Foundation\Application;
 use Illuminate\Contracts\Pagination\LengthAwarePaginator;
-use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Http\RedirectResponse;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
 use Illuminate\Http\Response;
-use Illuminate\Routing\Redirector;
-use Illuminate\Support\Facades\Auth;
 use Illuminate\Support\Facades\Gate;
-use Illuminate\Support\Facades\Validator;
-use function GuzzleHttp\Psr7\str;
+use Illuminate\View\View;
 
 class LogController extends Controller
 {
     /**
-     * Display a listing of the resource.
-     *
      * @param Request $request
-     * @return Application|LengthAwarePaginator|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @param LogFilters $filters
+     * @return Application|LengthAwarePaginator|Factory|View
      */
-    public function index(Request $request)
+    public function index(Request $request, LogFilters $filters)
     {
         if (!Gate::allows('日志-查询')) {
             return redirect(url('/'));
         }
-        //没有查询条件,默认展示最近50条
-        if (!$request->has('created_at_start') &&
-            !$request->has('created_at_end') &&
-            !$request->has('class') &&
-            !$request->has('method') &&
-            !$request->has('description') &&
-            !$request->has("is_exception")
-        ) {
-            $logs = Log::query()
-                ->with('user:id,name')
-                ->orderBy('id', 'desc')
-                ->paginate(50);
-            return view('maintenance.log.index', ['logs' => $logs]);
-        }
-        //不传开始时间提示错误信息并返回
-        if (!$request->has('created_at_start')) {
-            session()->flash('warning', '请选择开始时间');
-            return view('maintenance.log.index', ['logs' => null]);
-        }
-        $query = Log::query()->with('user:id,name');
-        if ($request->has('class')) {
-            $query->where('class', 'like', $request['class'] . '%');
-        }
-        if ($request->has('method')) {
-            $query->where('method', 'like', $request['method'] . '%');
-        }
-        if ($request->has('description')) {
-            $str = $request->description;
-            $str = trim($str, '\\');
-            $str = str_replace('\\', '\\\\', $str);
-            $query->where('description', 'like', '%' . $str . '%');
-        }
-        if ($request->has('created_at_start')) {
-            $query->where('created_at', '>=', $request->created_at_start." 00:00:00");
-        }
-        if ($request->has('created_at_end')) {
-            $query->where('created_at', '<=', $request->created_at_end." 23:59:59");
-        }
-        if ($request->has("is_exception")){
-            $query->where(function(Builder $query){
-                $query->where("method","like","ERROR%")->orWhere("method","like","EXCEPTION%");
-            });
-        }
-        $query->orderByDesc('id');
-        $logs = $query->with('user:id,name')->paginate($request->paginate??50);
-        return view('maintenance.log.index', ['logs' => $logs]);
+        $logs = Log::query()->filter($filters)->orderByDesc('id')->with('user:id,name')->paginate($request->input('paginate')??50);
+        return view('maintenance.log.index', compact('logs'));
     }
 
     /**
      * Display the specified resource.
      *
      * @param Log $log
-     * @return Application|\Illuminate\Contracts\View\Factory|Response|\Illuminate\View\View
+     * @return Application|Factory|Response|View
      */
     public function show(Log $log)
     {

+ 4 - 0
app/Log.php

@@ -32,4 +32,8 @@ class Log extends Model
 //            ' ',
 //            $value);
 //    }
+    public function scopeFilter($query, $filters)
+    {
+        return $filters->apply($query);
+    }
 }