diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f0fe927ad..aa04a3a16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,9 +6,9 @@ env: on: push: - branches: [ master ] + branches: [ master, 3.x] pull_request: - branches: [ master ] + branches: [ master, 3.x] # todo@1 remove 3.x before merge jobs: tests: diff --git a/assets/config.php b/assets/config.php index e1c82e6be..2abb2491b 100644 --- a/assets/config.php +++ b/assets/config.php @@ -33,6 +33,7 @@ Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper::class, Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper::class, // Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper::class, // Note: phpredis is needed + // Stancl\Tenancy\Bootstrappers\BatchTenancyBootstrapper::class, ], /** diff --git a/src/Bootstrappers/BatchTenancyBootstrapper.php b/src/Bootstrappers/BatchTenancyBootstrapper.php new file mode 100644 index 000000000..46143cef2 --- /dev/null +++ b/src/Bootstrappers/BatchTenancyBootstrapper.php @@ -0,0 +1,42 @@ +previousConnection = $batchRepository->getConnection(); + $batchRepository->setConnection(DB::connection('tenant')); + } + } + + public function revert() + { + if ($this->previousConnection) { + // Access the resolved batch repository instance and replace its connection with the previously replaced one + $batchRepository = app(BatchRepository::class); + $batchRepository->setConnection($this->previousConnection); + $this->previousConnection = null; + } + } +} diff --git a/tests/BatchTest.php b/tests/BatchTest.php new file mode 100644 index 000000000..1329d7819 --- /dev/null +++ b/tests/BatchTest.php @@ -0,0 +1,44 @@ +app->singleton(BatchTenancyBootstrapper::class); + + config([ + 'tenancy.bootstrappers' => [ + DatabaseTenancyBootstrapper::class, + BatchTenancyBootstrapper::class, + ], + ]); + + Event::listen(TenancyInitialized::class, BootstrapTenancy::class); + Event::listen(TenancyEnded::class, RevertToCentralContext::class); +}); + +test('batch repository is set to tenant connection and reverted', function () { + $tenant = Tenant::create(); + + expect(getBatchRepositoryConnectionName())->toBe('central'); + + tenancy()->initialize($tenant); + + expect(getBatchRepositoryConnectionName())->toBe('tenant'); + + tenancy()->end(); + + expect(getBatchRepositoryConnectionName())->toBe('central'); +})->skip(fn() => version_compare(app()->version(), '8.0', '<'), 'Job batches are only supported in Laravel 8+'); + +function getBatchRepositoryConnectionName() +{ + return app(BatchRepository::class)->getConnection()->getName(); +}