-
-
Save monodyle/087f23fb344c45a4c0630462a8bde4d8 to your computer and use it in GitHub Desktop.
Laravel Api profiling with duplication queries information.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Middleware; | |
| use Closure; | |
| use Illuminate\Http\JsonResponse; | |
| class ProfileJsonResponse | |
| { | |
| /** | |
| * Handle an incoming request. | |
| * Ref: https://github.com/barryvdh/laravel-debugbar/issues/252 | |
| * | |
| * @param \Illuminate\Http\Request $request | |
| * @param \Closure $next | |
| * @return mixed | |
| */ | |
| public function handle($request, Closure $next) | |
| { | |
| $response = $next($request); | |
| if ( | |
| $response instanceof JsonResponse && | |
| app()->bound('debugbar') && | |
| app('debugbar')->isEnabled() && | |
| is_object($response->getData()) | |
| ) { | |
| $debugData = app('debugbar')->getData(); | |
| // Adding duplicated queries information. | |
| $statements = collect($debugData['queries']['statements']); | |
| // Dùng array_count_values có thể sẽ nhanh hơn. | |
| $duplicated_queries = $statements->groupBy(function ($statement) { | |
| return $statement['sql']; | |
| })->map(function ($queries, $sql) { | |
| return [ | |
| 'sql' => $sql, | |
| 'count' => count($queries), | |
| 'hint' => 'Stop re-run same queries condition(Cache it by using php variable). Stop running queries in loop.' | |
| ]; | |
| })->sortByDesc('count')->values(); | |
| $debugData['queries']['duplication'] = $duplicated_queries; | |
| $response->setData($response->getData(true) + [ | |
| '_debugbar' => $debugData, | |
| ]); | |
| } | |
| return $response; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment