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; } } }