Files
SkinbaseNova/app/Support/AvatarUrl.php
2026-03-05 11:24:37 +01:00

62 lines
1.7 KiB
PHP

<?php
namespace App\Support;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
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://files.skinbase.org'), '/');
// Use hash-based path: avatars/ab/cd/{hash}/{size}.webp?v={hash}
$p1 = substr($avatarHash, 0, 2);
$p2 = substr($avatarHash, 2, 2);
$diskPath = sprintf('avatars/%s/%s/%s/%d.webp', $p1, $p2, $avatarHash, $size);
// Always use CDN-hosted avatar files.
return sprintf('%s/avatars/%s/%s/%s/%d.webp?v=%s', $base, $p1, $p2, $avatarHash, $size, $avatarHash);
}
public static function default(): string
{
$base = rtrim((string) config('cdn.avatar_url', 'https://files.skinbase.org'), '/');
return sprintf('%s/default/avatar_default.webp', $base);
}
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];
}
}