Skip to content

Commit

Permalink
Autodiscover Handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
TiiFuchs committed May 8, 2022
1 parent 0534b35 commit 776941c
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 2 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
],
"require": {
"php": "^8.1",
"guzzlehttp/guzzle": "^7.0"
"guzzlehttp/guzzle": "^7.0",
"symfony/finder": "^6.0"
},
"bin": [
"./telepathy"
Expand Down
63 changes: 62 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Handler/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,9 @@ abstract class Handler

abstract public function responsible(Update $update, TelegramBot $bot): bool;

public static function __set_state(array $an_array): object
{
return new static(...$an_array);
}

}
60 changes: 60 additions & 0 deletions src/TelegramBot.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,72 @@

namespace Tii\Telepath;

use Symfony\Component\Finder\Finder;
use Tii\Telepath\Handler\Handler;
use Tii\Telepath\Layer\Generated;
use Tii\Telepath\Telegram\Update;

class TelegramBot extends Generated
{

protected array $handlers = [];

public function discoverPsr4(string $path)
{
foreach (Finder::create()->files()->name('*.php')->in($path) as $file) {

// For Debugging
include_once $file->getRealPath();

$namespace = $this->getNamespace($file->getRealPath());
$class = $namespace . '\\' . $file->getBasename('.php');

foreach ((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {

$attributes = $method->getAttributes();

foreach ($attributes as $attribute) {

if (! is_subclass_of($attribute->getName(), Handler::class)) {
continue;
}

$this->handlers[] = [
'handler' => $attribute->newInstance(),
'class' => $class,
'method' => $method->getName()
];

}

}

}

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');
Expand Down

0 comments on commit 776941c

Please sign in to comment.