diff --git a/src/TelegramBot.php b/src/TelegramBot.php index 81d0f15..90b754a 100644 --- a/src/TelegramBot.php +++ b/src/TelegramBot.php @@ -35,7 +35,7 @@ public function discoverPsr4(string $path) $this->handlers[] = [ 'handler' => $attribute->newInstance(), 'class' => $class, - 'method' => $method->getName() + 'method' => $method->getName(), ]; } @@ -47,27 +47,6 @@ public function discoverPsr4(string $path) ray(var_export($this->handlers, true)); } - private function getNamespace(string $file): ?string - { - $tokens = token_get_all(file_get_contents($file)); - - $namespace = ''; - $namespaceKeyword = false; - foreach ($tokens as $token) { - if (is_array($token) && $token[0] === T_NAMESPACE) { - $namespaceKeyword = true; - } elseif ($namespaceKeyword && ! is_array($token) && $token === ';') { - break; - } elseif ($namespaceKeyword) { - $namespace .= is_array($token) ? $token[1] : $token; - } - } - - $namespace = trim($namespace); - - return $namespace ?: null; - } - public function handleWebhook(): bool { $input = file_get_contents('php://input'); @@ -84,24 +63,65 @@ public function handleWebhook(): bool $update = new Update($json); - // TODO: Call corresponding handler + $this->processUpdate($update); return true; } public function handlePolling(): never { + $offset = 0; while (true) { - $updates = $this->getUpdates(timeout: 60); + $updates = $this->getUpdates(timeout: 60, offset: $offset); foreach ($updates as $update) { - // TODO: Call corresponding handlers + $offset = max($offset, $update->update_id + 1); + $this->processUpdate($update); } } } + protected function processUpdate(Update $update) + { + /** + * @var Handler $handler + * @var string $class + * @var string $method + */ + foreach ($this->handlers as ['handler' => $handler, 'class' => $class, 'method' => $method]) { + + if ($handler->responsible($update, $this)) { + $instance = new $class; + $instance->$method($update, $this); + break; + } + + } + } + + private function getNamespace(string $file): ?string + { + $tokens = token_get_all(file_get_contents($file)); + + $namespace = ''; + $namespaceKeyword = false; + foreach ($tokens as $token) { + if (is_array($token) && $token[0] === T_NAMESPACE) { + $namespaceKeyword = true; + } elseif ($namespaceKeyword && ! is_array($token) && $token === ';') { + break; + } elseif ($namespaceKeyword) { + $namespace .= is_array($token) ? $token[1] : $token; + } + } + + $namespace = trim($namespace); + + return $namespace ?: null; + } + } \ No newline at end of file diff --git a/telepathy b/telepathy index c231d29..7f7876d 100755 Binary files a/telepathy and b/telepathy differ