Last active
November 30, 2018 03:27
-
-
Save khoinv/8823f5abcb992eb1b67ae2588a219a57 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 | |
| declare(strict_types=1); | |
| namespace App\Http\Middleware; | |
| use Closure; | |
| use Illuminate\Http\JsonResponse; | |
| /** | |
| * Class ApiStaffMiddleware | |
| * | |
| * @package App\Http\Middleware | |
| */ | |
| class ApiProfilingMiddleware | |
| { | |
| /** | |
| * Handle an incoming request. | |
| * | |
| * @param \Illuminate\Http\Request $request | |
| * @param Closure $next | |
| * | |
| * @return mixed | |
| */ | |
| public function handle($request, Closure $next) | |
| { | |
| $response = $next($request); | |
| return $this->decorateResponse($response); | |
| } | |
| /** | |
| * @param $response | |
| * | |
| * @return mixed | |
| */ | |
| private function decorateResponse($response) | |
| { | |
| 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']); | |
| // use array_count_values may make it run faster. | |
| $duplicated_queries = $statements->groupBy(function ($statement) { | |
| $prepared_statement = preg_replace("/('.+')/", '?', $statement['sql'], 1); | |
| return $prepared_statement; | |
| })->map(function ($queries, $prepared_statement) { | |
| return [ | |
| 'sql' => $prepared_statement, | |
| 'count' => count($queries), | |
| 'details' => collect($queries)->map(function ($query) { | |
| return $query['sql']; | |
| }), | |
| 'hint' => '1. Stop re-run same queries condition(Cache it by using php variable). | |
| 2. Stop running queries in loop. | |
| 3. Use whereIn or Eager loading' | |
| ]; | |
| })->filter(function ($data) { | |
| return $data['count'] > 1; | |
| })->sortByDesc('count')->values(); | |
| $debugData['queries']['DUPLICATION'] = $duplicated_queries; | |
| // Take it to the first of the array for easy view | |
| // $debugData = ['QUERIES_DUPLICATION' => $duplicated_queries] + $debugData; | |
| $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