76 lines
1.6 KiB
PHP
76 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Telegram;
|
|
|
|
use App\Models\User;
|
|
|
|
/**
|
|
* Request-scoped Telegram identity.
|
|
* null agent = official owner chat; otherwise the agent whose chat_id matched.
|
|
*/
|
|
class TelegramBotContext
|
|
{
|
|
private ?User $agent = null;
|
|
|
|
public function setAgent(?User $agent): void
|
|
{
|
|
$this->agent = $agent;
|
|
}
|
|
|
|
public function agent(): ?User
|
|
{
|
|
return $this->agent;
|
|
}
|
|
|
|
public function isOfficial(): bool
|
|
{
|
|
return $this->agent === null;
|
|
}
|
|
|
|
public function isAgent(): bool
|
|
{
|
|
return $this->agent !== null;
|
|
}
|
|
|
|
public function expectedChatId(): string
|
|
{
|
|
if ($this->agent !== null) {
|
|
return trim((string) ($this->agent->chat_id ?? ''));
|
|
}
|
|
|
|
return trim((string) config('coruna.telegram.owner_chat_id', ''));
|
|
}
|
|
|
|
/**
|
|
* Bind official vs agent from the incoming chat_id.
|
|
* Official owner_chat_id wins if it collides with an agent.
|
|
*/
|
|
public function bindFromChatId(int|string|null $chatId): bool
|
|
{
|
|
$chatId = trim((string) $chatId);
|
|
if ($chatId === '') {
|
|
$this->agent = null;
|
|
|
|
return false;
|
|
}
|
|
|
|
$owner = trim((string) config('coruna.telegram.owner_chat_id', ''));
|
|
if ($owner !== '' && $chatId === $owner) {
|
|
$this->agent = null;
|
|
|
|
return true;
|
|
}
|
|
|
|
$agent = User::findEnabledByChatId($chatId);
|
|
if ($agent === null) {
|
|
$this->agent = null;
|
|
|
|
return false;
|
|
}
|
|
|
|
$this->agent = $agent;
|
|
|
|
return true;
|
|
}
|
|
}
|