Skip to content

Commit

Permalink
Ensures connections only listen for their own events
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald committed Feb 22, 2023
1 parent 39f28e8 commit 13d76fa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Illuminate/Database/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
}
});
}

/**
Expand Down
26 changes: 26 additions & 0 deletions tests/Database/DatabaseConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 13d76fa

Please sign in to comment.