Seebad 0.3 stays in this release. With a single landlord every host still reaches the default website. Co-authored-by: Cursor <cursoragent@cursor.com>
68 lines
1.3 KiB
PHP
68 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Tenancy;
|
|
|
|
use App\Models\Tenant;
|
|
|
|
/**
|
|
* The landlord of the current request, job or command. Empty means "not chosen yet".
|
|
* While presence is required, a query on a tenant-owned model without a landlord fails closed.
|
|
*/
|
|
class TenantContext
|
|
{
|
|
private ?Tenant $tenant = null;
|
|
|
|
private bool $required = false;
|
|
|
|
public function set(Tenant $tenant): void
|
|
{
|
|
$this->tenant = $tenant;
|
|
}
|
|
|
|
public function forget(): void
|
|
{
|
|
$this->tenant = null;
|
|
$this->required = false;
|
|
}
|
|
|
|
public function get(): ?Tenant
|
|
{
|
|
return $this->tenant;
|
|
}
|
|
|
|
public function id(): ?int
|
|
{
|
|
return $this->tenant?->id;
|
|
}
|
|
|
|
public function requirePresence(bool $required = true): void
|
|
{
|
|
$this->required = $required;
|
|
}
|
|
|
|
public function isRequired(): bool
|
|
{
|
|
return $this->required;
|
|
}
|
|
|
|
/**
|
|
* Run a callback as $tenant, then restore whoever was current before.
|
|
*
|
|
* @template T
|
|
*
|
|
* @param callable(): T $callback
|
|
* @return T
|
|
*/
|
|
public function run(Tenant $tenant, callable $callback): mixed
|
|
{
|
|
$previous = $this->tenant;
|
|
$this->tenant = $tenant;
|
|
|
|
try {
|
|
return $callback();
|
|
} finally {
|
|
$this->tenant = $previous;
|
|
}
|
|
}
|
|
}
|