Skip to content

Commit

Permalink
Improvements in chat_id finding process
Browse files Browse the repository at this point in the history
  • Loading branch information
luzrain committed Feb 29, 2024
1 parent 7b9a2d3 commit 79ad7b5
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 18 deletions.
7 changes: 1 addition & 6 deletions src/TelegramCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,7 @@

abstract class TelegramCommand
{
private int|null $chatId = null;

public function setChatId(int|null $chatId): void
{
$this->chatId = $chatId;
}
public int|null $chatId = null;

protected function reply(
string $text,
Expand Down
23 changes: 12 additions & 11 deletions src/UpdateHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,23 @@ private function runController(string $controller, object $update, array $params
[$service, $method] = \explode('::', $controller, 2);
$controllerService = $this->serviceLocator->get($service);

$chatId = null;
if ($controllerService instanceof TelegramCommand) {
$controllerService->chatId = $this->findChatId($update);
}

return $controllerService->$method($update, ...$params);
}

private function findChatId(object $update): int|null
{
if ($update instanceof Update) {
foreach ($update as $updateItem) {
if (isset($updateItem->chat->id)) {
$chatId = $updateItem->chat->id;
break;
if (null !== $chatId = $updateItem->chat->id ?? $updateItem->message->chat->id ?? null) {
return $chatId;
}
}
} elseif (isset($update->chat->id)) {
$chatId = $update->chat->id;
}

if ($controllerService instanceof TelegramCommand) {
$controllerService->setChatId($chatId);
}

return $controllerService->$method($update, ...$params);
return $update->chat->id ?? $update->message->chat->id ?? null;
}
}
3 changes: 2 additions & 1 deletion tests/Controller/CallbackCommandController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Luzrain\TelegramBotBundle\Test\Controller;

use Luzrain\TelegramBotApi\EventCallbackReturn;
use Luzrain\TelegramBotApi\Method;
use Luzrain\TelegramBotBundle\Attribute\OnCallback;
use Luzrain\TelegramBotBundle\TelegramCommand;
Expand All @@ -12,7 +13,7 @@
final class CallbackCommandController extends TelegramCommand
{
#[OnCallback('test_callback_1')]
public function callback1(): Method
public function callback1(): Method|EventCallbackReturn
{
ControllerTestHelper::$isCallback1 = true;
return $this->reply('Callback1 answer');
Expand Down

0 comments on commit 79ad7b5

Please sign in to comment.