2023-02-16 14:22:18 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Models;
|
|
|
|
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
2023-12-16 19:09:38 +01:00
|
|
|
use Illuminate\Support\Facades\Cache;
|
2023-02-16 14:22:18 +01:00
|
|
|
|
|
|
|
class UserData extends Model
|
|
|
|
{
|
|
|
|
protected $table = 'users';
|
|
|
|
protected $fillable = ['image'];
|
|
|
|
|
|
|
|
public static function saveData($userId, $key, $value)
|
|
|
|
{
|
2023-12-16 19:09:38 +01:00
|
|
|
$userData = self::getCachedUserData($userId);
|
2023-02-16 14:22:18 +01:00
|
|
|
|
|
|
|
if (!$userData) {
|
2023-02-16 16:10:41 +01:00
|
|
|
return "null";
|
2023-02-16 14:22:18 +01:00
|
|
|
}
|
|
|
|
|
2023-02-16 16:10:41 +01:00
|
|
|
$data = json_decode($userData->image, true) ?? [];
|
2023-02-16 14:22:18 +01:00
|
|
|
$data[$key] = $value;
|
|
|
|
|
|
|
|
$userData->image = json_encode($data);
|
|
|
|
$userData->save();
|
2023-12-16 19:09:38 +01:00
|
|
|
|
|
|
|
self::cacheUserData($userId, $userData);
|
2023-02-16 14:22:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public static function getData($userId, $key)
|
|
|
|
{
|
2023-12-16 19:09:38 +01:00
|
|
|
$userData = self::getCachedUserData($userId);
|
|
|
|
|
2023-02-16 14:22:18 +01:00
|
|
|
if (!$userData || !$userData->image) {
|
2023-02-16 16:10:41 +01:00
|
|
|
return "null";
|
2023-02-16 14:22:18 +01:00
|
|
|
}
|
2023-12-16 19:09:38 +01:00
|
|
|
|
2023-02-16 16:10:41 +01:00
|
|
|
$data = json_decode($userData->image, true) ?? [];
|
2023-12-16 19:09:38 +01:00
|
|
|
|
2023-02-16 14:22:18 +01:00
|
|
|
return isset($data[$key]) ? $data[$key] : null;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function removeData($userId, $key)
|
|
|
|
{
|
2023-12-16 19:09:38 +01:00
|
|
|
$userData = self::getCachedUserData($userId);
|
|
|
|
|
2023-02-16 14:22:18 +01:00
|
|
|
if (!$userData || !$userData->image) {
|
2023-02-16 16:10:41 +01:00
|
|
|
return "null";
|
2023-02-16 14:22:18 +01:00
|
|
|
}
|
2023-12-16 19:09:38 +01:00
|
|
|
|
2023-02-16 16:10:41 +01:00
|
|
|
$data = json_decode($userData->image, true) ?? [];
|
2023-12-16 19:09:38 +01:00
|
|
|
|
2023-02-16 14:22:18 +01:00
|
|
|
if (isset($data[$key])) {
|
|
|
|
unset($data[$key]);
|
|
|
|
$userData->image = json_encode($data);
|
|
|
|
$userData->save();
|
2023-12-16 19:09:38 +01:00
|
|
|
|
|
|
|
self::cacheUserData($userId, $userData);
|
2023-02-16 14:22:18 +01:00
|
|
|
}
|
|
|
|
}
|
2023-12-16 19:09:38 +01:00
|
|
|
|
|
|
|
private static function getCachedUserData($userId)
|
|
|
|
{
|
|
|
|
return Cache::remember('user_data_' . $userId, now()->addMinutes(10), function () use ($userId) {
|
|
|
|
return self::where('id', $userId)->first();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private static function cacheUserData($userId, $userData)
|
|
|
|
{
|
|
|
|
Cache::put('user_data_' . $userId, $userData, now()->addMinutes(10));
|
|
|
|
}
|
2023-02-16 14:22:18 +01:00
|
|
|
}
|