diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..62d0391 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,74 @@ +name: run-tests + +on: + push: + branches: + - master + - dev + pull_request: + branches: + - master + +jobs: + php-tests: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php: ['8.4', '8.3', '8.2', '8.1', '8.0'] + laravel: ['8.*', '9.*', '10.*', '11.*', '12.*'] + dependency-version: [prefer-stable] + exclude: + - php: 8.0 + laravel: 10.* + - php: 8.0 + laravel: 11.* + - php: 8.0 + laravel: 12.* + - php: 8.1 + laravel: 11.* + - php: 8.1 + laravel: 12.* + - php: 8.2 + laravel: 8.* + - php: 8.3 + laravel: 8.* + - php: 8.3 + laravel: 9.* + - php: 8.4 + laravel: 8.* + - php: 8.4 + laravel: 9.* + include: + - laravel: 8.* + testbench: 6.23 + - laravel: 9.* + testbench: 7.* + - laravel: 10.* + testbench: 8.* + - laravel: 11.* + testbench: 9.* + - laravel: 12.* + testbench: 10.* + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick + coverage: none + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction + + - name: Execute tests + run: vendor/bin/phpunit \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2e1fc0e..219f39f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ build composer.lock -docs vendor coverage .idea -nbproject \ No newline at end of file +nbproject +.phpunit.result.cache diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index df16b68..0000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,19 +0,0 @@ -filter: - excluded_paths: [tests/*] - -checks: - php: - remove_extra_empty_lines: true - remove_php_closing_tag: true - remove_trailing_whitespace: true - fix_use_statements: - remove_unused: true - preserve_multiple: false - preserve_blanklines: true - order_alphabetically: true - fix_php_opening_tag: true - fix_linefeed: true - fix_line_ending: true - fix_identation_4spaces: true - fix_doc_comments: true - diff --git a/.styleci.yml b/.styleci.yml deleted file mode 100644 index f4d3cbc..0000000 --- a/.styleci.yml +++ /dev/null @@ -1,4 +0,0 @@ -preset: laravel - -disabled: - - single_class_element_per_statement diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 4084157..0000000 --- a/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: php - -php: - - 7.1 - - 7.2 - -env: - matrix: - - COMPOSER_FLAGS="--prefer-lowest" - - COMPOSER_FLAGS="" - -before_script: - - travis_retry composer self-update - - travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source - -script: - - vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover - -after_script: - - php vendor/bin/ocular code-coverage:upload --format=php-clover coverage.clover diff --git a/README.md b/README.md index f80cab1..dee3863 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,13 @@ # Laravel N+1 Query Detector [![Latest Version on Packagist](https://img.shields.io/packagist/v/beyondcode/laravel-query-detector.svg?style=flat-square)](https://packagist.org/packages/beyondcode/laravel-query-detector) -[![Build Status](https://img.shields.io/travis/beyondcode/laravel-query-detector/master.svg?style=flat-square)](https://travis-ci.org/beyondcode/laravel-query-detector) -[![Quality Score](https://img.shields.io/scrutinizer/g/beyondcode/laravel-query-detector.svg?style=flat-square)](https://scrutinizer-ci.com/g/beyondcode/laravel-query-detector) [![Total Downloads](https://img.shields.io/packagist/dt/beyondcode/laravel-query-detector.svg?style=flat-square)](https://packagist.org/packages/beyondcode/laravel-query-detector) The Laravel N+1 query detector helps you to increase your application's performance by reducing the number of queries it executes. This package monitors your queries in real-time, while you develop your application and notify you when you should add eager loading (N+1 queries). ![Example alert](https://beyondco.de/github/n+1/alert.png) + ## Installation You can install the package via composer: @@ -19,95 +18,10 @@ composer require beyondcode/laravel-query-detector --dev The package will automatically register itself. -## Usage - -If you run your application in the `debug` mode, the query monitor will be automatically active. So there is nothing you have to do. - -By default, this package will display an `alert()` message to notify you about an N+1 query found in the current request. - -If you rather want this information to be written to your `laravel.log` file, written to your browser's console log as a warning or listed in a new tab for the [Laravel Debugbar (barryvdh/laravel-debugbar)](https://github.com/barryvdh/laravel-debugbar), you can publish the configuration and change the output behaviour (see example below). - -You can publish the package's configuration using this command: - -```bash -php artisan vendor:publish --provider=BeyondCode\\QueryDetector\\QueryDetectorServiceProvider -``` - -This will add the `querydetector.php` file in your config directory with the following contents: - -```php - env('QUERY_DETECTOR_ENABLED', null), - - /* - * Threshold level for the N+1 query detection. If a relation query will be - * executed more then this amount, the detector will notify you about it. - */ - 'threshold' => 1, - - /* - * Here you can whitelist model relations. - * - * Right now, you need to define the model relation both as the class name and the attribute name on the model. - * So if an "Author" model would have a "posts" relation that points to a "Post" class, you need to add both - * the "posts" attribute and the "Post::class", since the relation can get resolved in multiple ways. - */ - 'except' => [ - //Author::class => [ - // Post::class, - // 'posts', - //] - ], - - /* - * Define the output format that you want to use. Multiple classes are supported. - * Available options are: - * - * Alert: - * Displays an alert on the website - * \BeyondCode\QueryDetector\Outputs\Alert::class - * - * Console: - * Writes the N+1 queries into your browsers console log - * \BeyondCode\QueryDetector\Outputs\Console::class - * - * Clockwork: (make sure you have the itsgoingd/clockwork package installed) - * Writes the N+1 queries warnings to Clockwork log - * \BeyondCode\QueryDetector\Outputs\Clockwork::class - * - * Debugbar: (make sure you have the barryvdh/laravel-debugbar package installed) - * Writes the N+1 queries into a custom messages collector of Debugbar - * \BeyondCode\QueryDetector\Outputs\Debugbar::class - * - * JSON: - * Writes the N+1 queries into the response body of your JSON responses - * \BeyondCode\QueryDetector\Outputs\Json::class - * - * Log: - * Writes the N+1 queries into the Laravel.log file - * \BeyondCode\QueryDetector\Outputs\Log::class - */ - 'output' => [ - \BeyondCode\QueryDetector\Outputs\Log::class, - \BeyondCode\QueryDetector\Outputs\Alert::class, - ] - -]; -``` - -If you use **Lumen**, you need to copy the config file manually and register the Lumen Service Provider in `bootstrap/app.php` file +## Documentation -```php -$app->register(\BeyondCode\QueryDetector\LumenQueryDetectorServiceProvider::class); -``` +You can find the documentation on our [website](http://beyondco.de/docs/laravel-query-detector). -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 diff --git a/composer.json b/composer.json index 116389e..e6da0e9 100644 --- a/composer.json +++ b/composer.json @@ -16,12 +16,13 @@ } ], "require": { - "php": "^7.1", - "illuminate/support": "5.5.*|5.6.*" + "php": "^7.1 || ^8.0", + "illuminate/support": "^5.5 || ^6.0 || ^7.0 || ^8.0 || ^9.0|^10.0 || ^11.0 || ^12.0" }, "require-dev": { - "orchestra/testbench": "3.6.*", - "phpunit/phpunit": "^7.0" + "laravel/legacy-factories": "^1.0", + "orchestra/testbench": "^3.0 || ^4.0 || ^5.0 || ^6.0|^8.0 || ^9.0 || ^10.0", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0 || ^10.5 || ^11.5.3" }, "autoload": { "psr-4": { @@ -36,7 +37,6 @@ "scripts": { "test": "vendor/bin/phpunit", "test-coverage": "vendor/bin/phpunit --coverage-html coverage" - }, "config": { "sort-packages": true diff --git a/config/config.php b/config/config.php index b7c63cf..84f1765 100644 --- a/config/config.php +++ b/config/config.php @@ -7,6 +7,12 @@ */ 'enabled' => env('QUERY_DETECTOR_ENABLED', null), + /* + * Threshold level for the N+1 query detection. If a relation query will be + * executed more than this amount, the detector will notify you about it. + */ + 'threshold' => (int) env('QUERY_DETECTOR_THRESHOLD', 1), + /* * Here you can whitelist model relations. * @@ -21,6 +27,13 @@ //] ], + /* + * Here you can set a specific log channel to write to + * in case you are trying to isolate queries or have a lot + * going on in the laravel.log. Defaults to laravel.log though. + */ + 'log_channel' => env('QUERY_DETECTOR_LOG_CHANNEL', 'daily'), + /* * Define the output format that you want to use. Multiple classes are supported. * Available options are: diff --git a/docs/_index.md b/docs/_index.md new file mode 100644 index 0000000..ed8a55e --- /dev/null +++ b/docs/_index.md @@ -0,0 +1,4 @@ +--- +packageName: Laravel Query Detector +githubUrl: https://github.com/beyondcode/laravel-query-detector +--- \ No newline at end of file diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..3559ca2 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,17 @@ +--- +title: Installation +order: 1 +--- +# Laravel N+1 Query Detector + +The Laravel N+1 query detector helps you to increase your application's performance by reducing the number of queries it executes. This package monitors your queries in real-time, while you develop your application and notify you when you should add eager loading (N+1 queries). + +# Installation + +You can install the package via composer: + +``` +composer require beyondcode/laravel-query-detector --dev +``` + +The package will automatically register itself. \ No newline at end of file diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..be34cfd --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,92 @@ +--- +title: Usage +order: 2 +--- + +## Usage + +If you run your application in the `debug` mode, the query monitor will be automatically active. So there is nothing you have to do. + +By default, this package will display an `alert()` message to notify you about an N+1 query found in the current request. + +If you rather want this information to be written to your `laravel.log` file, written to your browser's console log as a warning or listed in a new tab for the [Laravel Debugbar (barryvdh/laravel-debugbar)](https://github.com/barryvdh/laravel-debugbar), you can publish the configuration and change the output behaviour (see example below). + +You can publish the package's configuration using this command: + +```bash +php artisan vendor:publish --provider="BeyondCode\QueryDetector\QueryDetectorServiceProvider" +``` + +This will add the `querydetector.php` file in your config directory with the following contents: + +```php +return [ + /* + * Enable or disable the query detection. + * If this is set to "null", the app.debug config value will be used. + */ + 'enabled' => env('QUERY_DETECTOR_ENABLED', null), + + /* + * Threshold level for the N+1 query detection. If a relation query will be + * executed more then this amount, the detector will notify you about it. + */ + 'threshold' => (int) env('QUERY_DETECTOR_THRESHOLD', 1), + + /* + * Here you can whitelist model relations. + * + * Right now, you need to define the model relation both as the class name and the attribute name on the model. + * So if an "Author" model would have a "posts" relation that points to a "Post" class, you need to add both + * the "posts" attribute and the "Post::class", since the relation can get resolved in multiple ways. + */ + 'except' => [ + //Author::class => [ + // Post::class, + // 'posts', + //] + ], + + /* + * Define the output format that you want to use. Multiple classes are supported. + * Available options are: + * + * Alert: + * Displays an alert on the website + * \BeyondCode\QueryDetector\Outputs\Alert::class + * + * Console: + * Writes the N+1 queries into your browsers console log + * \BeyondCode\QueryDetector\Outputs\Console::class + * + * Clockwork: (make sure you have the itsgoingd/clockwork package installed) + * Writes the N+1 queries warnings to Clockwork log + * \BeyondCode\QueryDetector\Outputs\Clockwork::class + * + * Debugbar: (make sure you have the barryvdh/laravel-debugbar package installed) + * Writes the N+1 queries into a custom messages collector of Debugbar + * \BeyondCode\QueryDetector\Outputs\Debugbar::class + * + * JSON: + * Writes the N+1 queries into the response body of your JSON responses + * \BeyondCode\QueryDetector\Outputs\Json::class + * + * Log: + * Writes the N+1 queries into the Laravel.log file + * \BeyondCode\QueryDetector\Outputs\Log::class + */ + 'output' => [ + \BeyondCode\QueryDetector\Outputs\Log::class, + \BeyondCode\QueryDetector\Outputs\Alert::class, + ] + +]; +``` + +If you use **Lumen**, you need to copy the config file manually and register the Lumen Service Provider in `bootstrap/app.php` file + +```php +$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.) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 1eef57c..5119f0b 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,12 +1,7 @@ @@ -14,16 +9,4 @@ tests - - - src/ - - - - - - - - - diff --git a/src/Outputs/Clockwork.php b/src/Outputs/Clockwork.php index 533bcbd..fea7055 100644 --- a/src/Outputs/Clockwork.php +++ b/src/Outputs/Clockwork.php @@ -7,6 +7,11 @@ class Clockwork implements Output { + public function boot() + { + // + } + public function output(Collection $detectedQueries, Response $response) { clock()->warning("{$detectedQueries->count()} N+1 queries detected:", $detectedQueries->toArray()); diff --git a/src/Outputs/Console.php b/src/Outputs/Console.php index 6b4680f..7a90366 100644 --- a/src/Outputs/Console.php +++ b/src/Outputs/Console.php @@ -42,10 +42,10 @@ protected function getOutputContent(Collection $detectedQueries) $output .= "console.warn('Found the following N+1 queries in this request:\\n\\n"; foreach ($detectedQueries as $detectedQuery) { $output .= "Model: ".addslashes($detectedQuery['model'])." => Relation: ".addslashes($detectedQuery['relation']); - $output .= " - You should add \"with(\'".$detectedQuery['relation']."\')\" to eager-load this relation."; + $output .= " - You should add \"with(\'".addslashes($detectedQuery['relation'])."\')\" to eager-load this relation."; $output .= "\\n\\n"; $output .= "Model: ".addslashes($detectedQuery['model'])."\\n"; - $output .= "Relation: ".$detectedQuery['relation']."\\n"; + $output .= "Relation: ".addslashes($detectedQuery['relation'])."\\n"; $output .= "Num-Called: ".$detectedQuery['count']."\\n"; $output .= "\\n"; $output .= 'Call-Stack:\\n'; diff --git a/src/Outputs/Debugbar.php b/src/Outputs/Debugbar.php index 31ff9c0..ea887aa 100644 --- a/src/Outputs/Debugbar.php +++ b/src/Outputs/Debugbar.php @@ -5,7 +5,7 @@ use Illuminate\Support\Collection; use Symfony\Component\HttpFoundation\Response; -use Debugbar as LaravelDebugbar; +use Barryvdh\Debugbar\Facade as LaravelDebugbar; use DebugBar\DataCollector\MessagesCollector; class Debugbar implements Output @@ -15,8 +15,10 @@ class Debugbar implements Output public function boot() { $this->collector = new MessagesCollector('N+1 Queries'); - - LaravelDebugbar::addCollector($this->collector); + + if (!LaravelDebugbar::hasCollector($this->collector->getName())) { + LaravelDebugbar::addCollector($this->collector); + } } public function output(Collection $detectedQueries, Response $response) diff --git a/src/Outputs/Json.php b/src/Outputs/Json.php index 21b387e..e2f5714 100644 --- a/src/Outputs/Json.php +++ b/src/Outputs/Json.php @@ -16,6 +16,10 @@ public function output(Collection $detectedQueries, Response $response) { if ($response instanceof JsonResponse) { $data = $response->getData(true); + if (! is_array($data)){ + $data = [ $data ]; + } + $data['warning_queries'] = $detectedQueries; $response->setData($data); } diff --git a/src/Outputs/Log.php b/src/Outputs/Log.php index 2c9349f..7563530 100644 --- a/src/Outputs/Log.php +++ b/src/Outputs/Log.php @@ -2,7 +2,7 @@ namespace BeyondCode\QueryDetector\Outputs; -use Log as LaravelLog; +use Illuminate\Support\Facades\Log as LaravelLog; use Illuminate\Support\Collection; use Symfony\Component\HttpFoundation\Response; @@ -15,17 +15,27 @@ public function boot() public function output(Collection $detectedQueries, Response $response) { - LaravelLog::info('Detected N+1 Query'); + $this->log('Detected N+1 Query'); + foreach ($detectedQueries as $detectedQuery) { - LaravelLog::info('Model: '.$detectedQuery['model']); - LaravelLog::info('Relation: '.$detectedQuery['relation']); - LaravelLog::info('Num-Called: '.$detectedQuery['count']); + $logOutput = 'Model: '.$detectedQuery['model'] . PHP_EOL; + + $logOutput .= 'Relation: '.$detectedQuery['relation'] . PHP_EOL; - LaravelLog::info('Call-Stack:'); + $logOutput .= 'Num-Called: '.$detectedQuery['count'] . PHP_EOL; + + $logOutput .= 'Call-Stack:' . PHP_EOL; foreach ($detectedQuery['sources'] as $source) { - LaravelLog::info('#'.$source->index.' '.$source->name.':'.$source->line); + $logOutput .= '#'.$source->index.' '.$source->name.':'.$source->line . PHP_EOL; } + + $this->log($logOutput); } } + + private function log(string $message) + { + LaravelLog::channel(config('querydetector.log_channel'))->info($message); + } } diff --git a/src/QueryDetector.php b/src/QueryDetector.php index c9b316f..f48e5d2 100755 --- a/src/QueryDetector.php +++ b/src/QueryDetector.php @@ -2,7 +2,8 @@ namespace BeyondCode\QueryDetector; -use DB; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Database\Eloquent\Builder; use Symfony\Component\HttpFoundation\Response; @@ -13,15 +14,29 @@ class QueryDetector { /** @var Collection */ private $queries; + /** + * @var bool + */ + private $booted = false; - public function __construct() + private function resetQueries() { $this->queries = Collection::make(); } + public function __construct() + { + $this->resetQueries(); + } + public function boot() { - DB::listen(function($query) { + if ($this->booted) { + $this->resetQueries(); + return; + } + + DB::listen(function ($query) { $backtrace = collect(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 50)); $this->logQuery($query, $backtrace); @@ -31,6 +46,8 @@ public function boot() app()->singleton($outputType); app($outputType)->boot(); } + + $this->booted = true; } public function isEnabled(): bool @@ -47,17 +64,17 @@ public function isEnabled(): bool public function logQuery($query, Collection $backtrace) { $modelTrace = $backtrace->first(function ($trace) { - return array_get($trace, 'object') instanceof Builder; + return Arr::get($trace, 'object') instanceof Builder; }); // The query is coming from an Eloquent model - if (! is_null($modelTrace)) { + if (!is_null($modelTrace)) { /* * Relations get resolved by either calling the "getRelationValue" method on the model, * or if the class itself is a Relation. */ $relation = $backtrace->first(function ($trace) { - return array_get($trace, 'function') === 'getRelationValue' || array_get($trace, 'class') === Relation::class ; + return Arr::get($trace, 'function') === 'getRelationValue' || Arr::get($trace, 'class') === Relation::class; }); // We try to access a relation @@ -73,13 +90,19 @@ public function logQuery($query, Collection $backtrace) } $sources = $this->findSource($backtrace); + + if (empty($sources)) { + return; + } $key = md5($query->sql . $model . $relationName . $sources[0]->name . $sources[0]->line); - $count = array_get($this->queries, $key.'.count', 0); + $count = Arr::get($this->queries, $key . '.count', 0); + $time = Arr::get($this->queries, $key . '.time', 0); $this->queries[$key] = [ 'count' => ++$count, + 'time' => $time + $query->time, 'query' => $query->sql, 'model' => $model, 'relatedModel' => $relatedModel, @@ -103,7 +126,7 @@ protected function findSource($stack) public function parseTrace($index, array $trace) { - $frame = (object) [ + $frame = (object)[ 'index' => $index, 'name' => null, 'line' => isset($trace['line']) ? $trace['line'] : '?', @@ -188,7 +211,7 @@ protected function getOutputTypes() { $outputTypes = config('querydetector.output'); - if (! is_array($outputTypes)) { + if (!is_array($outputTypes)) { $outputTypes = [$outputTypes]; } @@ -210,4 +233,9 @@ public function output($request, $response) return $response; } + + public function emptyQueries() + { + $this->queries = Collection::make(); + } } diff --git a/src/QueryDetectorServiceProvider.php b/src/QueryDetectorServiceProvider.php index 8d62987..4efac27 100644 --- a/src/QueryDetectorServiceProvider.php +++ b/src/QueryDetectorServiceProvider.php @@ -15,7 +15,7 @@ public function boot() if ($this->app->runningInConsole()) { $this->publishes([ __DIR__.'/../config/config.php' => config_path('querydetector.php'), - ], 'config'); + ], 'query-detector-config'); } $this->registerMiddleware(QueryDetectorMiddleware::class); diff --git a/tests/QueryDetectorTest.php b/tests/QueryDetectorTest.php index b428e2a..f2dbe0d 100644 --- a/tests/QueryDetectorTest.php +++ b/tests/QueryDetectorTest.php @@ -34,6 +34,54 @@ public function it_detects_n1_query_on_properties() $this->assertSame('profile', $queries[0]['relation']); } + /** @test */ + public function it_detects_n1_query_on_multiple_requests() + { + Route::get('/', function (){ + $authors = Author::get(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + // first request + $this->get('/'); + $queries = app(QueryDetector::class)->getDetectedQueries(); + $this->assertCount(1, $queries); + $this->assertSame(Author::count(), $queries[0]['count']); + $this->assertSame(Author::class, $queries[0]['model']); + $this->assertSame('profile', $queries[0]['relation']); + + // second request + $this->get('/'); + $queries = app(QueryDetector::class)->getDetectedQueries(); + $this->assertCount(1, $queries); + $this->assertSame(Author::count(), $queries[0]['count']); + $this->assertSame(Author::class, $queries[0]['model']); + $this->assertSame('profile', $queries[0]['relation']); + } + + /** @test */ + public function it_does_not_detect_a_false_n1_query_on_multiple_requests() + { + Route::get('/', function (){ + $authors = Author::with("profile")->get(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + // first request + $this->get('/'); + $this->assertCount(0, app(QueryDetector::class)->getDetectedQueries()); + + // second request + $this->get('/'); + $this->assertCount(0, app(QueryDetector::class)->getDetectedQueries()); + } + /** @test */ public function it_ignores_eager_loaded_relationships() { @@ -288,4 +336,27 @@ public function it_uses_the_trace_line_to_detect_queries() $this->assertSame(Author::class, $queries[0]['model']); $this->assertSame('profile', $queries[0]['relation']); } + + /** @test */ + public function it_empty_queries() + { + Route::get('/', function (){ + $authors = Author::all(); + + foreach ($authors as $author) { + $author->profile; + } + }); + + $this->get('/'); + + $queryDetector = app(QueryDetector::class); + + $queries = $queryDetector->getDetectedQueries(); + $this->assertCount(1, $queries); + + $queryDetector->emptyQueries(); + $queries = $queryDetector->getDetectedQueries(); + $this->assertCount(0, $queries); + } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 6f669c4..b981a0a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -12,7 +12,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase { protected static $setUpRun = false; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -79,4 +79,4 @@ protected function setUpDatabase() $table->morphs('commentable'); }); } -} \ No newline at end of file +}