From 13d76faf707029fc7401b3d6daac3d0e7aa9581e Mon Sep 17 00:00:00 2001 From: Tim MacDonald Date: Thu, 23 Feb 2023 10:29:07 +1100 Subject: [PATCH] Ensures connections only listen for their own events --- src/Illuminate/Database/Connection.php | 8 +++++-- tests/Database/DatabaseConnectionTest.php | 26 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Database/Connection.php b/src/Illuminate/Database/Connection.php index a45c563458ad..28bbc9217d97 100755 --- a/src/Illuminate/Database/Connection.php +++ b/src/Illuminate/Database/Connection.php @@ -108,7 +108,7 @@ class Connection implements ConnectionInterface /** * The event dispatcher instance. * - * @var \Illuminate\Contracts\Events\Dispatcher + * @var \Illuminate\Contracts\Events\Dispatcher|null */ protected $events; @@ -965,7 +965,11 @@ public function beforeExecuting(Closure $callback) */ public function listen(Closure $callback) { - $this->events?->listen(Events\QueryExecuted::class, $callback); + $this->events?->listen(Events\QueryExecuted::class, function ($event) use ($callback) { + if ($event->connection === $this) { + $callback(); + } + }); } /** diff --git a/tests/Database/DatabaseConnectionTest.php b/tests/Database/DatabaseConnectionTest.php index 5b21b36fe416..5c9ba471a873 100755 --- a/tests/Database/DatabaseConnectionTest.php +++ b/tests/Database/DatabaseConnectionTest.php @@ -18,6 +18,7 @@ use Illuminate\Database\Query\Processors\Processor; use Illuminate\Database\QueryException; use Illuminate\Database\Schema\Builder; +use Illuminate\Events\Dispatcher as EventsDispatcher; use Mockery as m; use PDO; use PDOException; @@ -475,6 +476,31 @@ public function testSchemaBuilderCanBeCreated() $this->assertSame($connection, $schema->getConnection()); } + public function testConnectionListenerIsScopedToCurrentInstance() + { + $events = new EventsDispatcher(); + $mysql = (new Connection(new DatabaseConnectionTestMockPDO))->setEventDispatcher($events); + $sqlite = (new Connection(new DatabaseConnectionTestMockPDO))->setEventDispatcher($events); + $mysqlQueries = $sqliteQueries = 0; + $mysql->listen(function () use (&$mysqlQueries) { + $mysqlQueries++; + }); + $sqlite->listen(function () use (&$sqliteQueries) { + $sqliteQueries++; + }); + + $mysql->pretend(function ($connection) { + $connection->table('foo')->count(); + }); + $sqlite->pretend(function ($connection) { + $connection->table('foo')->count(); + $connection->table('foo')->count(); + }); + + $this->assertSame(1, $mysqlQueries); + $this->assertSame(2, $sqliteQueries); + } + protected function getMockConnection($methods = [], $pdo = null) { $pdo = $pdo ?: new DatabaseConnectionTestMockPDO;