diff --git a/src/Database/Models/Tenant.php b/src/Database/Models/Tenant.php index 88c34146..83e75332 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 @@ -45,6 +46,17 @@ class Tenant extends Model implements Contracts\Tenant return $this->getAttribute($this->getTenantKeyName()); } + public static function current(): static|null + { + return tenant(); + } + + /** @throws TenancyNotInitializedException */ + public static function currentOrFail(): static + { + 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 b4fd38f6..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]); @@ -141,6 +142,31 @@ test('a command can be run on a collection of tenants', function () { expect(Tenant::find('t2')->foo)->toBe('xyz'); }); +test('the current method returns the currently initialized tenant', function() { + tenancy()->initialize($tenant = Tenant::create()); + + expect(Tenant::current())->toBe($tenant); +}); + +test('the current method returns null if there is no currently initialized tenant', function() { + tenancy()->end(); + + 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';