Skip to content

Commit

Permalink
feat: make it extendable
Browse files Browse the repository at this point in the history
  • Loading branch information
muhammadmp97 committed Jun 11, 2022
1 parent 96a9a6d commit 705ea81
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ Then use it like this:
'reply_markup' => $keyboard,
]);

### Extend it!
You may want to add some methods to TeleBot class to improve your code readability and avoid duplication. Look at this simple example as an inspiration:

TeleBot::extend('isReply', function () {
return property_exists($this->message, 'reply_to_message');
});

// if ($tg->isReply()) { ... }

## Have you seen a problem?

Create an issue and explain your problem!
Expand Down
10 changes: 10 additions & 0 deletions src/TeleBot.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,12 @@

use TeleBot\Util\Http;
use TeleBot\Exceptions\TeleBotException;
use TeleBot\Traits\Extendable;

class TeleBot
{
use Extendable;

private $endpoint = 'https://api.telegram.org/bot';
public $update;

Expand Down Expand Up @@ -112,6 +115,13 @@ private function createRegexPattern($command)

public function __call($name, $params)
{
if (static::hasExtension($name)) {
$extension = static::$extensions[$name];
$extension = $extension->bindTo($this, static::class);

return $extension(...$params);
}

$httpResponse = Http::post($this->endpoint . $name, $params[0]);

if (!$httpResponse->ok) {
Expand Down
18 changes: 18 additions & 0 deletions src/Traits/extendable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace TeleBot\Traits;

trait Extendable
{
private static $extensions = [];

public static function extend(string $name, callable $extension)
{
static::$extensions[$name] = $extension;
}

private static function hasExtension(string $name)
{
return in_array($name, array_keys(static::$extensions));
}
}

0 comments on commit 705ea81

Please sign in to comment.