Skip to content

Commit 30c3400

Browse files
authored
Merge pull request #16 from miamibc/database-orm
Database orm
2 parents a7ccdde + 886d3b3 commit 30c3400

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+1100
-437
lines changed

autoload.php

+4
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,7 @@
1616
// dotenv
1717
$dotenv = Dotenv\Dotenv::create(dirname(__FILE__));
1818
$dotenv->load();
19+
20+
// RedbeanPHP (ORM)
21+
use RedBeanPHP\R;
22+
R::setup( 'sqlite:data/sqlite.db' );

composer.json

+2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
"vlucas/phpdotenv": "^3.4",
2121
"alrik11es/cowsayphp": "^1.2",
2222
"league/html-to-markdown": "^4.9",
23+
"gabordemooij/redbean": "dev-master",
24+
"cheprasov/php-redis-client": "^1.10"
2325
},
2426
"autoload": {
2527
"psr-4": {

joker.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
// these plugins never stops processing of other plugins
1515
// (never returns false or Joker\Bot::PLUGIN_BREAK)
1616
new Joker\Plugin\Log( ['file' =>'data/log/log.json'] ),
17+
new Joker\Plugin\Activity( ['sync_time' => 60] ),
1718
new Joker\Plugin\Forwarder( [
1819
['from' => -343502518, 'text' => ['*покуп*'], 'to' => -343502518, ],
1920
['from' => -343502518, 'text' => ['*прода*', '*сдаё*'], 'to' => -343502518, 'forward' => false ],
@@ -29,7 +30,7 @@
2930
new Joker\Plugin\Cowsay( ['bg_color' =>'#222222','text_color' =>'#dadada']),
3031
new Joker\Plugin\Hello(),
3132
new Joker\Plugin\Sticker(),
32-
new Joker\Plugin\Carma(['clean_time' => 10,'power_time' => 600,'start_carma' => 10]),
33+
new Joker\Plugin\Carma(['clean_time' => false, 'power_time' => 600,'start_carma' => 10]),
3334
new Joker\Plugin\Quote( ['dir' =>'data/jokes'] ),
3435
new Joker\Plugin\Corona( ['file' => 'data/corona/today.csv', 'update_hours'=>3]),
3536
new Joker\Plugin\Currency(),

phpunit.xml.dist

+3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
<testsuite name="Plugin">
1313
<directory suffix="Test.php">./tests/Plugin</directory>
1414
</testsuite>
15+
<testsuite name="Database">
16+
<directory suffix="Test.php">./tests/Database</directory>
17+
</testsuite>
1518
</testsuites>
1619
<coverage processUncoveredFiles="true">
1720
<include>

src/Bot.php

+6-4
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,22 @@ class Bot
3636

3737
public function __construct( $token, $debug = false )
3838
{
39-
if ( $token && strlen($token) < 40)
40-
throw new Exception("Please provide Telegram API token. More info https://core.telegram.org/bots#3-how-do-i-create-a-bot");
39+
40+
// No token given, start bot without access HTTP and Telegram Bot API, you can test something else...
41+
// @see QuoteTest::testTelegramQuoteConverter
42+
if (!$token) return;
4143

4244
$this->token = $token;
4345
$this->debug = $debug;
4446
$this->ch = curl_init();
4547

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

5456
}
5557

src/Database/Redis.php

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
/**
3+
*
4+
* @package joker-telegram-bot
5+
* @author Sergei Miami <[email protected]>
6+
*/
7+
8+
namespace Joker\Database;
9+
10+
use RedisClient\RedisClient;
11+
12+
trait Redis
13+
{
14+
15+
private $redis_cache;
16+
17+
private function getRedisKey()
18+
{
19+
$class = explode('\\', get_class( $this ) );
20+
$class = strtolower(end($class));
21+
return "joker/$class/". $this->id();
22+
}
23+
24+
public function getRedis()
25+
{
26+
// is already loaded, return it
27+
if (!is_null($this->redis_cache))
28+
return $this->redis_cache;
29+
30+
$class = explode('\\', get_class( $this ) );
31+
$class = strtolower(end($class));
32+
33+
$client = new RedisClient();
34+
$json = $client->get("joker/$class/". $this->id());
35+
$object = is_null($json) ? new \stdClass() : json_decode( $json );
36+
return $this->redis_cache = $object;
37+
}
38+
39+
public function saveRedis()
40+
{
41+
if (!is_null($this->redis_cache))
42+
{
43+
$class = explode('\\', get_class( $this ) );
44+
$class = strtolower(end($class));
45+
46+
$client = new RedisClient();
47+
$client->set( $this->getRedisKey() , json_encode($this->redis_cache));
48+
}
49+
return $this;
50+
}
51+
52+
public function cleanRedis()
53+
{
54+
$client = new RedisClient();
55+
$client->del( $this->getRedisKey() );
56+
return $this;
57+
}
58+
59+
}

src/Database/Sqlite.php

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
/**
3+
*
4+
* @package joker-telegram-bot
5+
* @author Sergei Miami <[email protected]>
6+
*/
7+
8+
namespace Joker\Database;
9+
10+
use RedBeanPHP\R;
11+
12+
trait Sqlite
13+
{
14+
15+
private $sqlite_cache;
16+
17+
public function getCustom()
18+
{
19+
// is already loaded, return it
20+
if (!is_null($this->sqlite_cache))
21+
return $this->sqlite_cache;
22+
23+
// try to read from database
24+
// table name is last word in class signature
25+
$class = explode('\\', get_class( $this ) );
26+
$class = strtolower(end($class));
27+
28+
// try to find by uuid
29+
if (!$item = R::findOne( $class, 'uuid =?', [ $this->id() ]))
30+
{
31+
// if not found, create
32+
$item = R::dispense( $class );
33+
$item->uuid = $this->id();
34+
}
35+
36+
// store in cache and return
37+
return $this->sqlite_cache = $item;
38+
}
39+
40+
public function saveCustom()
41+
{
42+
if (!is_null($this->sqlite_cache))
43+
R::store($this->sqlite_cache);
44+
45+
return $this;
46+
}
47+
48+
public function cleanCustom()
49+
{
50+
if (!is_null($this->sqlite_cache))
51+
R::trash($this->sqlite_cache);
52+
53+
return $this;
54+
}
55+
56+
}

src/Event.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ public function getTags()
105105
];
106106
}
107107

108-
public function getMessage()
108+
public function message()
109109
{
110110
return new Message( $this->data['message'] );
111111
}

src/Parser/Animation.php

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
/**
3+
* Telegram Bot API parser for Joker
4+
*
5+
* @package joker-telegram-bot
6+
* @author Sergei Miami <[email protected]>
7+
*/
8+
9+
namespace Joker\Parser;
10+
11+
/**
12+
* This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
13+
* @see https://core.telegram.org/bots/api#animation
14+
*
15+
* @method string file_id() Identifier for this file, which can be used to download or reuse the file
16+
* @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.
17+
* @method integer width() Video width as defined by sender
18+
* @method integer height() Video height as defined by sender
19+
* @method integer duration() Duration of the video in seconds as defined by sender
20+
* @method PhotoSize thumb() Optional. Animation thumbnail as defined by sender
21+
* @method string file_name() Optional. Original animation filename as defined by sender
22+
* @method string mime_type() Optional. MIME type of the file as defined by sender
23+
* @method integer file_size() Optional. File size
24+
*/
25+
class Animation extends Base
26+
{
27+
28+
protected $wrapper = [
29+
'thumb' => PhotoSize::class,
30+
];
31+
32+
33+
}

src/Parser/Audio.php

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
/**
3+
* Telegram Bot API parser for Joker
4+
*
5+
* @package joker-telegram-bot
6+
* @author Sergei Miami <[email protected]>
7+
*/
8+
9+
namespace Joker\Parser;
10+
11+
/**
12+
* This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
13+
* @see https://core.telegram.org/bots/api#audio
14+
*
15+
* @method string file_id() Identifier for this file, which can be used to download or reuse the file
16+
* @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.
17+
* @method integer duration() Duration of the audio in seconds as defined by sender
18+
* @method string performer() Optional. Performer of the audio as defined by sender or by audio tags
19+
* @method string title() Optional. Title of the audio as defined by sender or by audio tags
20+
* @method string file_name() Optional. Original filename as defined by sender
21+
* @method string mime_type() Optional. MIME type of the file as defined by sender
22+
* @method integer file_size() Optional. File size
23+
* @method PhotoSize thumb() Optional. Thumbnail of the album cover to which the music file belongs
24+
*/
25+
class Audio extends Base
26+
{
27+
28+
protected $wrapper = [
29+
'thumb' => PhotoSize::class,
30+
];
31+
32+
33+
}

src/Parser/Base.php

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php
2+
/**
3+
* Telegram Bot API parser for Joker
4+
*
5+
* @package joker-telegram-bot
6+
* @author Sergei Miami <[email protected]>
7+
*/
8+
9+
namespace Joker\Parser;
10+
11+
12+
class Base
13+
{
14+
15+
protected $data = []; // incoming data array
16+
protected $cache = []; // wrapped objects cache
17+
protected $wrapper = []; // array or wrappers
18+
19+
public function __construct( $data )
20+
{
21+
$this->data = $data;
22+
}
23+
24+
/**
25+
* Get data, wrapped if possible
26+
* @param $key
27+
*
28+
* @return false|mixed
29+
*/
30+
public function __call($key, $arguments)
31+
{
32+
// no data with this key, return false
33+
if (!isset($this->data[$key])) return false;
34+
35+
// no wrapper for this key, return data no need to cache
36+
if (!isset($this->wrapper[$key])) return $this->data[$key];
37+
38+
// cache exists, return it
39+
if (isset($this->cache[$key])) return $this->cache[$key];
40+
41+
// wrap and save to cache
42+
$wrapper = $this->wrapper[$key];
43+
$data = $this->data[$key];
44+
45+
// data is sequental array, result will be array of wrapped elements
46+
if (is_array( $data ) && array_keys($data) === range(0, count($data) - 1))
47+
{
48+
$result = array_map(function ( $item ) use ($wrapper){
49+
return new $wrapper( $item );
50+
}, $data);
51+
}
52+
// all other types of data, just wrap it
53+
else
54+
{
55+
$result = new $wrapper($data);
56+
}
57+
return $this->cache[$key] = $result;
58+
}
59+
60+
public function getData()
61+
{
62+
return $this->data;
63+
}
64+
65+
}

0 commit comments

Comments
 (0)