Skip to content

Commit

Permalink
Merge pull request #16 from miamibc/database-orm
Browse files Browse the repository at this point in the history
Database orm
  • Loading branch information
miamibc authored May 16, 2021
2 parents a7ccdde + 886d3b3 commit 30c3400
Show file tree
Hide file tree
Showing 47 changed files with 1,100 additions and 437 deletions.
4 changes: 4 additions & 0 deletions autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@
// dotenv
$dotenv = Dotenv\Dotenv::create(dirname(__FILE__));
$dotenv->load();

// RedbeanPHP (ORM)
use RedBeanPHP\R;
R::setup( 'sqlite:data/sqlite.db' );
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
"vlucas/phpdotenv": "^3.4",
"alrik11es/cowsayphp": "^1.2",
"league/html-to-markdown": "^4.9",
"gabordemooij/redbean": "dev-master",
"cheprasov/php-redis-client": "^1.10"
},
"autoload": {
"psr-4": {
Expand Down
3 changes: 2 additions & 1 deletion joker.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// these plugins never stops processing of other plugins
// (never returns false or Joker\Bot::PLUGIN_BREAK)
new Joker\Plugin\Log( ['file' =>'data/log/log.json'] ),
new Joker\Plugin\Activity( ['sync_time' => 60] ),
new Joker\Plugin\Forwarder( [
['from' => -343502518, 'text' => ['*покуп*'], 'to' => -343502518, ],
['from' => -343502518, 'text' => ['*прода*', '*сдаё*'], 'to' => -343502518, 'forward' => false ],
Expand All @@ -29,7 +30,7 @@
new Joker\Plugin\Cowsay( ['bg_color' =>'#222222','text_color' =>'#dadada']),
new Joker\Plugin\Hello(),
new Joker\Plugin\Sticker(),
new Joker\Plugin\Carma(['clean_time' => 10,'power_time' => 600,'start_carma' => 10]),
new Joker\Plugin\Carma(['clean_time' => false, 'power_time' => 600,'start_carma' => 10]),
new Joker\Plugin\Quote( ['dir' =>'data/jokes'] ),
new Joker\Plugin\Corona( ['file' => 'data/corona/today.csv', 'update_hours'=>3]),
new Joker\Plugin\Currency(),
Expand Down
3 changes: 3 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
<testsuite name="Plugin">
<directory suffix="Test.php">./tests/Plugin</directory>
</testsuite>
<testsuite name="Database">
<directory suffix="Test.php">./tests/Database</directory>
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
Expand Down
10 changes: 6 additions & 4 deletions src/Bot.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,22 @@ class Bot

public function __construct( $token, $debug = false )
{
if ( $token && strlen($token) < 40)
throw new Exception("Please provide Telegram API token. More info https://core.telegram.org/bots#3-how-do-i-create-a-bot");

// No token given, start bot without access HTTP and Telegram Bot API, you can test something else...
// @see QuoteTest::testTelegramQuoteConverter
if (!$token) return;

$this->token = $token;
$this->debug = $debug;
$this->ch = curl_init();

// display information, or throw an error
$this->me = $this->getMe();
if (!$this->me->getId())
if (!$this->me->id())
{
throw new Exception("Wrong or inactive Telegram API token. More info https://core.telegram.org/bots#6-botfather");
}
echo "\nBot started: "; print_r($this->me);
echo "\nBot started: "; print_r( $this->me->getData() );

}

Expand Down
59 changes: 59 additions & 0 deletions src/Database/Redis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/**
*
* @package joker-telegram-bot
* @author Sergei Miami <[email protected]>
*/

namespace Joker\Database;

use RedisClient\RedisClient;

trait Redis
{

private $redis_cache;

private function getRedisKey()
{
$class = explode('\\', get_class( $this ) );
$class = strtolower(end($class));
return "joker/$class/". $this->id();
}

public function getRedis()
{
// is already loaded, return it
if (!is_null($this->redis_cache))
return $this->redis_cache;

$class = explode('\\', get_class( $this ) );
$class = strtolower(end($class));

$client = new RedisClient();
$json = $client->get("joker/$class/". $this->id());
$object = is_null($json) ? new \stdClass() : json_decode( $json );
return $this->redis_cache = $object;
}

public function saveRedis()
{
if (!is_null($this->redis_cache))
{
$class = explode('\\', get_class( $this ) );
$class = strtolower(end($class));

$client = new RedisClient();
$client->set( $this->getRedisKey() , json_encode($this->redis_cache));
}
return $this;
}

public function cleanRedis()
{
$client = new RedisClient();
$client->del( $this->getRedisKey() );
return $this;
}

}
56 changes: 56 additions & 0 deletions src/Database/Sqlite.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php
/**
*
* @package joker-telegram-bot
* @author Sergei Miami <[email protected]>
*/

namespace Joker\Database;

use RedBeanPHP\R;

trait Sqlite
{

private $sqlite_cache;

public function getCustom()
{
// is already loaded, return it
if (!is_null($this->sqlite_cache))
return $this->sqlite_cache;

// try to read from database
// table name is last word in class signature
$class = explode('\\', get_class( $this ) );
$class = strtolower(end($class));

// try to find by uuid
if (!$item = R::findOne( $class, 'uuid =?', [ $this->id() ]))
{
// if not found, create
$item = R::dispense( $class );
$item->uuid = $this->id();
}

// store in cache and return
return $this->sqlite_cache = $item;
}

public function saveCustom()
{
if (!is_null($this->sqlite_cache))
R::store($this->sqlite_cache);

return $this;
}

public function cleanCustom()
{
if (!is_null($this->sqlite_cache))
R::trash($this->sqlite_cache);

return $this;
}

}
2 changes: 1 addition & 1 deletion src/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public function getTags()
];
}

public function getMessage()
public function message()
{
return new Message( $this->data['message'] );
}
Expand Down
33 changes: 33 additions & 0 deletions src/Parser/Animation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
/**
* Telegram Bot API parser for Joker
*
* @package joker-telegram-bot
* @author Sergei Miami <[email protected]>
*/

namespace Joker\Parser;

/**
* This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
* @see https://core.telegram.org/bots/api#animation
*
* @method string file_id() Identifier for this file, which can be used to download or reuse the file
* @method string file_unique_id() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
* @method integer width() Video width as defined by sender
* @method integer height() Video height as defined by sender
* @method integer duration() Duration of the video in seconds as defined by sender
* @method PhotoSize thumb() Optional. Animation thumbnail as defined by sender
* @method string file_name() Optional. Original animation filename as defined by sender
* @method string mime_type() Optional. MIME type of the file as defined by sender
* @method integer file_size() Optional. File size
*/
class Animation extends Base
{

protected $wrapper = [
'thumb' => PhotoSize::class,
];


}
33 changes: 33 additions & 0 deletions src/Parser/Audio.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
/**
* Telegram Bot API parser for Joker
*
* @package joker-telegram-bot
* @author Sergei Miami <[email protected]>
*/

namespace Joker\Parser;

/**
* This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
* @see https://core.telegram.org/bots/api#audio
*
* @method string file_id() Identifier for this file, which can be used to download or reuse the file
* @method string file_unique_id() Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
* @method integer duration() Duration of the audio in seconds as defined by sender
* @method string performer() Optional. Performer of the audio as defined by sender or by audio tags
* @method string title() Optional. Title of the audio as defined by sender or by audio tags
* @method string file_name() Optional. Original filename as defined by sender
* @method string mime_type() Optional. MIME type of the file as defined by sender
* @method integer file_size() Optional. File size
* @method PhotoSize thumb() Optional. Thumbnail of the album cover to which the music file belongs
*/
class Audio extends Base
{

protected $wrapper = [
'thumb' => PhotoSize::class,
];


}
65 changes: 65 additions & 0 deletions src/Parser/Base.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php
/**
* Telegram Bot API parser for Joker
*
* @package joker-telegram-bot
* @author Sergei Miami <[email protected]>
*/

namespace Joker\Parser;


class Base
{

protected $data = []; // incoming data array
protected $cache = []; // wrapped objects cache
protected $wrapper = []; // array or wrappers

public function __construct( $data )
{
$this->data = $data;
}

/**
* Get data, wrapped if possible
* @param $key
*
* @return false|mixed
*/
public function __call($key, $arguments)
{
// no data with this key, return false
if (!isset($this->data[$key])) return false;

// no wrapper for this key, return data no need to cache
if (!isset($this->wrapper[$key])) return $this->data[$key];

// cache exists, return it
if (isset($this->cache[$key])) return $this->cache[$key];

// wrap and save to cache
$wrapper = $this->wrapper[$key];
$data = $this->data[$key];

// data is sequental array, result will be array of wrapped elements
if (is_array( $data ) && array_keys($data) === range(0, count($data) - 1))
{
$result = array_map(function ( $item ) use ($wrapper){
return new $wrapper( $item );
}, $data);
}
// all other types of data, just wrap it
else
{
$result = new $wrapper($data);
}
return $this->cache[$key] = $result;
}

public function getData()
{
return $this->data;
}

}
Loading

0 comments on commit 30c3400

Please sign in to comment.