mirror of
https://github.com/SophiaAtkinson/steamwidgets-web.git
synced 2026-01-17 09:33:30 -08:00
base redis commit
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Redis;
|
||||
|
||||
/**
|
||||
* Class SteamUser
|
||||
*
|
||||
@@ -12,13 +14,22 @@ class SteamUser
|
||||
/**
|
||||
* Query item data from Steam
|
||||
*
|
||||
* @param $appid
|
||||
* @param $lang
|
||||
* @param $key
|
||||
* @param $steamid
|
||||
* @return mixed
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function querySteamData($key, $steamid)
|
||||
{
|
||||
// Generate cache key
|
||||
$cacheKey = 'steam_user_' . $steamid;
|
||||
|
||||
// Check if data is cached
|
||||
$cachedData = self::getFromCache($cacheKey);
|
||||
if ($cachedData !== false) {
|
||||
return json_decode($cachedData);
|
||||
}
|
||||
|
||||
$url = self::STEAM_ENDPOINT . "?key={$key}&steamids={$steamid}";
|
||||
|
||||
$handle = curl_init($url);
|
||||
@@ -30,7 +41,7 @@ class SteamUser
|
||||
$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 +49,49 @@ class SteamUser
|
||||
$obj = json_decode($response);
|
||||
|
||||
if (isset($obj->response->players[0])) {
|
||||
return $obj->response->players[0];
|
||||
$userData = $obj->response->players[0];
|
||||
|
||||
// Store data in cache
|
||||
self::setToCache($cacheKey, json_encode($userData));
|
||||
|
||||
return $userData;
|
||||
}
|
||||
|
||||
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