103 lines
2.2 KiB
PHP
103 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Support\ManagedTenants;
|
|
|
|
use App\Models\Tenant;
|
|
use Illuminate\Support\Facades\Session;
|
|
|
|
final class ManagedTenantContext
|
|
{
|
|
public const CURRENT_TENANT_ID_SESSION_KEY = 'managed_tenants.current_id';
|
|
|
|
public const ARCHIVED_TENANT_ID_SESSION_KEY = 'managed_tenants.archived_id';
|
|
|
|
public static function setCurrentTenant(Tenant $tenant): void
|
|
{
|
|
Session::put(self::CURRENT_TENANT_ID_SESSION_KEY, (int) $tenant->getKey());
|
|
Session::forget(self::ARCHIVED_TENANT_ID_SESSION_KEY);
|
|
}
|
|
|
|
public static function setArchivedTenant(Tenant $tenant): void
|
|
{
|
|
Session::put(self::ARCHIVED_TENANT_ID_SESSION_KEY, (int) $tenant->getKey());
|
|
}
|
|
|
|
public static function currentTenantId(): ?int
|
|
{
|
|
$id = Session::get(self::CURRENT_TENANT_ID_SESSION_KEY);
|
|
|
|
if (is_int($id)) {
|
|
return $id;
|
|
}
|
|
|
|
if (is_string($id) && ctype_digit($id)) {
|
|
return (int) $id;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static function archivedTenantId(): ?int
|
|
{
|
|
$id = Session::get(self::ARCHIVED_TENANT_ID_SESSION_KEY);
|
|
|
|
if (is_int($id)) {
|
|
return $id;
|
|
}
|
|
|
|
if (is_string($id) && ctype_digit($id)) {
|
|
return (int) $id;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static function currentTenant(): ?Tenant
|
|
{
|
|
$id = self::currentTenantId();
|
|
|
|
if (! is_int($id)) {
|
|
return null;
|
|
}
|
|
|
|
$tenant = Tenant::query()->find($id);
|
|
|
|
if (! $tenant?->isActive()) {
|
|
self::clearCurrentTenant();
|
|
|
|
return null;
|
|
}
|
|
|
|
return $tenant;
|
|
}
|
|
|
|
public static function archivedTenant(): ?Tenant
|
|
{
|
|
$id = self::archivedTenantId();
|
|
|
|
if (! is_int($id)) {
|
|
return null;
|
|
}
|
|
|
|
return Tenant::withTrashed()->find($id);
|
|
}
|
|
|
|
public static function clear(): void
|
|
{
|
|
self::clearCurrentTenant();
|
|
self::clearArchivedTenant();
|
|
}
|
|
|
|
public static function clearCurrentTenant(): void
|
|
{
|
|
Session::forget(self::CURRENT_TENANT_ID_SESSION_KEY);
|
|
}
|
|
|
|
public static function clearArchivedTenant(): void
|
|
{
|
|
Session::forget(self::ARCHIVED_TENANT_ID_SESSION_KEY);
|
|
}
|
|
}
|