mirror of
https://github.com/SophiaAtkinson/steamwidgets-web.git
synced 2025-06-27 21:07:40 -07:00
base redis commit
This commit is contained in:
@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Redis;
|
||||
|
||||
/**
|
||||
* Class SteamServer
|
||||
*
|
||||
@ -8,17 +10,25 @@
|
||||
class SteamServer
|
||||
{
|
||||
const STEAM_ENDPOINT = 'https://api.steampowered.com/IGameServersService/GetServerList/v1/';
|
||||
|
||||
/**
|
||||
* Query item data from Steam
|
||||
*
|
||||
* @param $appid
|
||||
* @param $lang
|
||||
* @param $key
|
||||
* @param $addr
|
||||
* @return mixed
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function querySteamData($key, $addr)
|
||||
{
|
||||
// Generate cache key
|
||||
$cacheKey = 'steam_server_' . md5($key . $addr);
|
||||
|
||||
// Check if data is cached
|
||||
$cachedData = self::getFromCache($cacheKey);
|
||||
if ($cachedData !== false) {
|
||||
return json_decode($cachedData);
|
||||
}
|
||||
|
||||
$url = self::STEAM_ENDPOINT . "?key={$key}&filter=addr\\{$addr}";
|
||||
|
||||
$handle = curl_init($url);
|
||||
@ -30,7 +40,7 @@ class SteamServer
|
||||
$response = curl_exec($handle);
|
||||
|
||||
if(curl_error($handle) !== '') {
|
||||
throw new \Exception('cURL error occured');
|
||||
throw new \Exception('cURL error occurred');
|
||||
}
|
||||
|
||||
curl_close($handle);
|
||||
@ -38,9 +48,49 @@ class SteamServer
|
||||
$obj = json_decode($response);
|
||||
|
||||
if (isset($obj->response->servers[0])) {
|
||||
return $obj->response->servers[0];
|
||||
$serverData = $obj->response->servers[0];
|
||||
|
||||
// Store data in cache
|
||||
self::setToCache($cacheKey, json_encode($serverData));
|
||||
|
||||
return $serverData;
|
||||
}
|
||||
|
||||
throw new \Exception('Invalid data response');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get data from Redis cache
|
||||
*
|
||||
* @param $key
|
||||
* @return mixed|bool
|
||||
*/
|
||||
private static function getFromCache($key)
|
||||
{
|
||||
$redis = new Redis();
|
||||
$redis->connect(env('REDIS_HOST'), env('REDIS_PORT'));
|
||||
$redis->select(env('REDIS_DATABASE')); // Selecting Redis database index 5
|
||||
|
||||
$cachedData = $redis->get($key);
|
||||
if ($cachedData !== false) {
|
||||
return json_decode($cachedData);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set data to Redis cache
|
||||
*
|
||||
* @param $key
|
||||
* @param $value
|
||||
*/
|
||||
private static function setToCache($key, $value)
|
||||
{
|
||||
$redis = new Redis();
|
||||
$redis->connect(env('REDIS_HOST'), env('REDIS_PORT'));
|
||||
$redis->select(env('REDIS_DATABASE')); // Selecting Redis database index 5
|
||||
|
||||
$redis->set($key, json_encode($value), env('REDIS_EXPIRATION'));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user