From 38ca7748ce434781640b276c72135028b0770c54 Mon Sep 17 00:00:00 2001 From: Alex Clark <38124722+alexthekiwi@users.noreply.github.com> Date: Wed, 12 Jul 2023 00:39:51 +1200 Subject: [PATCH] Add support for commenting multiple database connections (#13) --- config/sql-commenter.php | 8 ++++++++ src/SqlCommenterServiceProvider.php | 27 +++++++++++++++++---------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/config/sql-commenter.php b/config/sql-commenter.php index cb31e92..0089cab 100644 --- a/config/sql-commenter.php +++ b/config/sql-commenter.php @@ -28,4 +28,12 @@ * the SqlCommenter class and specify your custom class here */ 'commenter_class' => Spatie\SqlCommenter\SqlCommenter::class, + + /** + * The database connections for which you want to add comments. + * Defaults to the default connection defined in config/database.php + */ + 'connections' => [ + // 'mysql', + ], ]; diff --git a/src/SqlCommenterServiceProvider.php b/src/SqlCommenterServiceProvider.php index 878f0e4..740f4d7 100644 --- a/src/SqlCommenterServiceProvider.php +++ b/src/SqlCommenterServiceProvider.php @@ -3,6 +3,7 @@ namespace Spatie\SqlCommenter; use Illuminate\Database\Connection; +use Illuminate\Support\Facades\DB; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; use Spatie\SqlCommenter\Commenters\Commenter; @@ -29,18 +30,24 @@ public function packageBooted(): void return new $commenterClass(); }); - $this->app->get('db.connection') - ->beforeExecuting(function ( - string &$query, - array &$bindings, - Connection $connection, - ) { - $sqlCommenter = app(SqlCommenter::class); - $commenters = $this->instanciateCommenters(config('sql-commenter.commenters')); + $connections = config('sql-commenter.connections', []); - $query = $sqlCommenter->commentQuery($query, $connection, $commenters); - }); + if (empty($connections)) { + $connections = [config('database.default')]; + } + + collect($connections)->each(fn (string $conn) => DB::connection($conn)->beforeExecuting(function ( + string &$query, + array &$bindings, + Connection $connection, + ) { + $sqlCommenter = app(SqlCommenter::class); + + $commenters = $this->instanciateCommenters(config('sql-commenter.commenters')); + + $query = $sqlCommenter->commentQuery($query, $connection, $commenters); + })); } /**