72 lines
1.4 KiB
PHP
72 lines
1.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Support;
|
|
|
|
final class TenantContext
|
|
{
|
|
private ?string $tenantCode = null;
|
|
|
|
public function set(string $tenantCode): void
|
|
{
|
|
if ($tenantCode === '') {
|
|
throw new \InvalidArgumentException('tenant_code 不能为空。');
|
|
}
|
|
|
|
$this->tenantCode = $tenantCode;
|
|
}
|
|
|
|
public function forget(): void
|
|
{
|
|
$this->tenantCode = null;
|
|
}
|
|
|
|
public function has(): bool
|
|
{
|
|
return $this->tenantCode !== null;
|
|
}
|
|
|
|
public function get(): ?string
|
|
{
|
|
return $this->tenantCode;
|
|
}
|
|
|
|
public function code(): string
|
|
{
|
|
if ($this->tenantCode === null) {
|
|
throw new MissingTenantContextException;
|
|
}
|
|
|
|
return $this->tenantCode;
|
|
}
|
|
|
|
public function cacheKey(string $key): string
|
|
{
|
|
return 'tenant:'.$this->code().':'.$key;
|
|
}
|
|
|
|
public function lockKey(string $key): string
|
|
{
|
|
return 'lock:tenant:'.$this->code().':'.$key;
|
|
}
|
|
|
|
/**
|
|
* @template T
|
|
*
|
|
* @param callable(): T $callback
|
|
* @return T
|
|
*/
|
|
public function run(string $tenantCode, callable $callback): mixed
|
|
{
|
|
$previous = $this->tenantCode;
|
|
$this->set($tenantCode);
|
|
|
|
try {
|
|
return $callback();
|
|
} finally {
|
|
$this->tenantCode = $previous;
|
|
}
|
|
}
|
|
}
|