51 lines
1.2 KiB
PHP
51 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class AvatarUrl
|
|
{
|
|
private static array $hashCache = [];
|
|
|
|
public static function forUser(int $userId, ?string $hash = null, int $size = 128): string
|
|
{
|
|
if ($userId <= 0) {
|
|
return self::default();
|
|
}
|
|
|
|
$avatarHash = $hash ?: self::resolveHash($userId);
|
|
if (!$avatarHash) {
|
|
return self::default();
|
|
}
|
|
|
|
$base = rtrim((string) config('cdn.avatar_url', 'https://file.skinbase.org'), '/');
|
|
|
|
return sprintf('%s/avatars/%d/%d.webp?v=%s', $base, $userId, $size, $avatarHash);
|
|
}
|
|
|
|
public static function default(): string
|
|
{
|
|
return asset('img/default-avatar.webp');
|
|
}
|
|
|
|
private static function resolveHash(int $userId): ?string
|
|
{
|
|
if (array_key_exists($userId, self::$hashCache)) {
|
|
return self::$hashCache[$userId];
|
|
}
|
|
|
|
try {
|
|
$value = DB::table('user_profiles')
|
|
->where('user_id', $userId)
|
|
->value('avatar_hash');
|
|
} catch (\Throwable $e) {
|
|
$value = null;
|
|
}
|
|
|
|
self::$hashCache[$userId] = $value ? (string) $value : null;
|
|
|
|
return self::$hashCache[$userId];
|
|
}
|
|
}
|