diff --git a/README.md b/README.md index 714e991..50d77c4 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,8 @@ If you use **Lumen**, you need to copy the config file manually and register the $this->app->register(\BeyondCode\QueryDetector\LumenQueryDetectorServiceProvider::class); ``` +If you need additional logic to run when the package detects unoptimized queries, you can listen to the `\BeyondCode\QueryDetector\Events\QueryDetected` event and write a listener to run your own handler. (e.g. send warning to Sentry/Bugsnag, send Slack notification, etc.) + ### Testing ``` bash diff --git a/src/Events/QueryDetected.php b/src/Events/QueryDetected.php new file mode 100644 index 0000000..635ac4f --- /dev/null +++ b/src/Events/QueryDetected.php @@ -0,0 +1,26 @@ +queries = $queries; + } + + /** + * @return Collection + */ + public function getQueries() + { + return $this->queries; + } +} diff --git a/src/QueryDetector.php b/src/QueryDetector.php index ada50e8..3db2a80 100755 --- a/src/QueryDetector.php +++ b/src/QueryDetector.php @@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Builder; use Symfony\Component\HttpFoundation\Response; use Illuminate\Database\Eloquent\Relations\Relation; +use BeyondCode\QueryDetector\Events\QueryDetected; class QueryDetector { @@ -167,7 +168,13 @@ public function getDetectedQueries(): Collection } } - return $queries->where('count', '>', config('querydetector.threshold', 1))->values(); + $queries = $queries->where('count', '>', config('querydetector.threshold', 1))->values(); + + if ($queries->isNotEmpty()) { + event(new QueryDetected($queries)); + } + + return $queries; } protected function applyOutput(Response $response) diff --git a/tests/QueryDetectorTest.php b/tests/QueryDetectorTest.php index 48405e0..c0b144b 100644 --- a/tests/QueryDetectorTest.php +++ b/tests/QueryDetectorTest.php @@ -3,7 +3,9 @@ namespace BeyondCode\QueryDetector\Tests; use Route; +use Illuminate\Support\Facades\Event; use BeyondCode\QueryDetector\QueryDetector; +use BeyondCode\QueryDetector\Events\QueryDetected; use BeyondCode\QueryDetector\Tests\Models\Post; use BeyondCode\QueryDetector\Tests\Models\Author; use BeyondCode\QueryDetector\Tests\Models\Comment; @@ -224,4 +226,40 @@ public function it_ignores_redirects() $this->assertCount(1, $queries); } + + /** @test */ + public function it_fires_an_event_if_detects_n1_query() + { + Event::fake(); + + Route::get('/', function (){ + $authors = Author::all(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + $this->get('/'); + + Event::assertDispatched(QueryDetected::class); + } + + /** @test */ + public function it_does_not_fire_an_event_if_there_is_no_n1_query() + { + Event::fake(); + + Route::get('/', function (){ + $authors = Author::with('profile')->get(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + $this->get('/'); + + Event::assertNotDispatched(QueryDetected::class); + } }