From e5700e7f72e5bb5d93279a4e05f4e743edd87c75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?michael=20lundb=C3=B8l?= Date: Sat, 24 Oct 2020 05:29:41 +0200 Subject: [PATCH] Add runGlobal helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: michael lundbøl --- src/Tenancy.php | 21 +++++++++++++++ tests/AutomaticModeTest.php | 54 +++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/src/Tenancy.php b/src/Tenancy.php index 307f818f..2ecb923e 100644 --- a/src/Tenancy.php +++ b/src/Tenancy.php @@ -85,6 +85,27 @@ class Tenancy return array_map('app', $resolve($this->tenant)); } + /** + * @param callable $callback + * @return mixed + */ + public function runGlobal(callable $callback) + { + $oldTenant = $this->tenant; + + if ($this->initialized) { + $this->end(); + } + + $result = $callback(); + + if ($oldTenant) { + $this->initialize($oldTenant); + } + + return $result; + } + public function query(): Builder { return $this->model()->query(); diff --git a/tests/AutomaticModeTest.php b/tests/AutomaticModeTest.php index c9d08879..06bc789f 100644 --- a/tests/AutomaticModeTest.php +++ b/tests/AutomaticModeTest.php @@ -71,10 +71,58 @@ class AutomaticModeTest extends TestCase $this->assertSame('foobar', app('tenancy_initialized_for_tenant')); } + + /** @test */ + public function running_the_global_tenancy_helper_with_tenant_already_initialized() + { + MyBootstrapper::$revertedCallCount = 0; + GlobalRun::$count = 0; + + config(['tenancy.bootstrappers' => [ + MyBootstrapper::class, + ]]); + + $tenant = Tenant::create([ + 'id' => 'acme', + ]); + + tenancy()->initialize($tenant); + + $this->assertSame('acme', app('tenancy_initialized_for_tenant')); + + tenancy()->runGlobal(function () { + GlobalRun::$count = 1; + }); + + $this->assertSame(1, MyBootstrapper::$revertedCallCount); + $this->assertSame(1, GlobalRun::$count); + $this->assertSame('acme', app('tenancy_initialized_for_tenant')); + } + + /** @test */ + public function running_the_global_tenancy_helper_with_tenant_not_already_initialized() + { + MyBootstrapper::$revertedCallCount = 0; + GlobalRun::$count = 0; + + config(['tenancy.bootstrappers' => [ + MyBootstrapper::class, + ]]); + + tenancy()->runGlobal(function () { + GlobalRun::$count = 1; + }); + + $this->assertSame(0, MyBootstrapper::$revertedCallCount); + $this->assertSame(1, GlobalRun::$count); + $this->assertFalse(app()->bound('tenancy_initialized_for_tenant')); + } } class MyBootstrapper implements TenancyBootstrapper { + public static $revertedCallCount = 0; + public function bootstrap(\Stancl\Tenancy\Contracts\Tenant $tenant) { app()->instance('tenancy_initialized_for_tenant', $tenant->getTenantKey()); @@ -82,6 +130,12 @@ class MyBootstrapper implements TenancyBootstrapper public function revert() { + static::$revertedCallCount++; app()->instance('tenancy_ended', true); } } + +class GlobalRun { + + public static $count = 0; +}