2016-09-03 04:24:22 +05:30
|
|
|
<?php
|
2024-12-02 15:40:55 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2016-09-03 04:24:22 +05:30
|
|
|
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;
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
final readonly class SessionModel {
|
2016-09-03 04:24:22 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
private const int KEY_TIME = 120; // 2 min
|
2016-09-03 04:24:22 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function __construct(
|
|
|
|
public string $username,
|
|
|
|
public string $serverId,
|
|
|
|
) {
|
2016-09-03 04:24:22 +05:30
|
|
|
}
|
|
|
|
|
2017-09-19 22:36:16 +05:30
|
|
|
public static function find(string $username, string $serverId): ?self {
|
2024-12-02 15:40:55 +05:30
|
|
|
$key = self::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;
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
$data = json_decode((string)$result, true);
|
2016-09-03 04:24:22 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
return new self($data['username'], $data['serverId']);
|
2016-09-03 04:24:22 +05:30
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function save(): mixed {
|
|
|
|
$key = self::buildKey($this->username, $this->serverId);
|
2016-09-03 04:24:22 +05:30
|
|
|
$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
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function delete(): mixed {
|
|
|
|
return Yii::$app->redis->del(self::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]);
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
protected static function buildKey(string $username, string $serverId): string {
|
2016-09-03 04:24:22 +05:30
|
|
|
return md5('minecraft:join-server:' . mb_strtolower($username) . ':' . $serverId);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|