2016-09-03 04:24:22 +05:30
|
|
|
<?php
|
|
|
|
namespace api\modules\session\models;
|
|
|
|
|
2016-09-06 15:26:39 +05:30
|
|
|
use common\models\Account;
|
2016-09-03 04:24:22 +05:30
|
|
|
use Yii;
|
|
|
|
|
|
|
|
class SessionModel {
|
|
|
|
|
2018-04-18 02:17:25 +05:30
|
|
|
private const KEY_TIME = 120; // 2 min
|
2016-09-03 04:24:22 +05:30
|
|
|
|
|
|
|
public $username;
|
|
|
|
|
|
|
|
public $serverId;
|
|
|
|
|
|
|
|
public function __construct(string $username, string $serverId) {
|
|
|
|
$this->username = $username;
|
|
|
|
$this->serverId = $serverId;
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public static function find(string $username, string $serverId): ?self {
|
2016-09-03 04:24:22 +05:30
|
|
|
$key = static::buildKey($username, $serverId);
|
2018-07-08 20:50:19 +05:30
|
|
|
$result = Yii::$app->redis->get($key);
|
2016-09-03 04:24:22 +05:30
|
|
|
if (!$result) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
$data = json_decode($result, true);
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
return new static($data['username'], $data['serverId']);
|
2016-09-03 04:24:22 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function save() {
|
|
|
|
$key = static::buildKey($this->username, $this->serverId);
|
|
|
|
$data = json_encode([
|
|
|
|
'username' => $this->username,
|
|
|
|
'serverId' => $this->serverId,
|
|
|
|
]);
|
|
|
|
|
2018-07-08 20:50:19 +05:30
|
|
|
return Yii::$app->redis->setex($key, self::KEY_TIME, $data);
|
2016-09-03 04:24:22 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function delete() {
|
2018-07-08 20:50:19 +05:30
|
|
|
return Yii::$app->redis->del(static::buildKey($this->username, $this->serverId));
|
2016-09-03 04:24:22 +05:30
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public function getAccount(): ?Account {
|
2016-09-06 15:26:39 +05:30
|
|
|
return Account::findOne(['username' => $this->username]);
|
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
protected static function buildKey($username, $serverId): string {
|
2016-09-03 04:24:22 +05:30
|
|
|
return md5('minecraft:join-server:' . mb_strtolower($username) . ':' . $serverId);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|