From 54a4258fa429bf51e1d75b3afd12648fac741dd6 Mon Sep 17 00:00:00 2001 From: lukinovec Date: Mon, 10 Oct 2022 15:12:04 +0200 Subject: [PATCH] Add and test `Tenant::currentOrFail()` --- src/Database/Models/Tenant.php | 6 ++++++ tests/TenantModelTest.php | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/Database/Models/Tenant.php b/src/Database/Models/Tenant.php index bbaab7a3..183e94ce 100644 --- a/src/Database/Models/Tenant.php +++ b/src/Database/Models/Tenant.php @@ -10,6 +10,7 @@ use Stancl\Tenancy\Contracts; use Stancl\Tenancy\Database\Concerns; use Stancl\Tenancy\Database\TenantCollection; use Stancl\Tenancy\Events; +use Stancl\Tenancy\Exceptions\TenancyNotInitializedException; /** * @property string|int $id @@ -50,6 +51,11 @@ class Tenant extends Model implements Contracts\Tenant return tenant(); } + public static function currentOrFail(): Tenant + { + return static::current() ?? throw new TenancyNotInitializedException; + } + public function newCollection(array $models = []): TenantCollection { return new TenantCollection($models); diff --git a/tests/TenantModelTest.php b/tests/TenantModelTest.php index 40dfa996..fb62260c 100644 --- a/tests/TenantModelTest.php +++ b/tests/TenantModelTest.php @@ -18,6 +18,7 @@ use Stancl\Tenancy\Jobs\CreateDatabase; use Stancl\Tenancy\Listeners\BootstrapTenancy; use Stancl\Tenancy\Tests\Etc\Tenant; use Stancl\Tenancy\UUIDGenerator; +use Stancl\Tenancy\Exceptions\TenancyNotInitializedException; test('created event is dispatched', function () { Event::fake([TenantCreated::class]); @@ -153,6 +154,19 @@ test('the current method returns null if there is no currently initialized tenan expect(Tenant::current())->toBeNull(); }); +test('currentOrFail method returns the currently initialized tenant', function() { + tenancy()->initialize($tenant = Tenant::create()); + + expect(Tenant::currentOrFail())->toBe($tenant); +}); + +test('currentOrFail method throws an exception if there is no currently initialized tenant', function() { + tenancy()->end(); + + expect(fn() => Tenant::currentOrFail())->toThrow(TenancyNotInitializedException::class); +}); + + class MyTenant extends Tenant { protected $table = 'tenants';