Add country flag

This commit is contained in:
DariusIII
2026-01-27 16:36:03 +01:00
parent 12f60d19d3
commit d05eee801f
3 changed files with 58 additions and 1 deletions
+30
View File
@@ -421,6 +421,36 @@ final class User extends Authenticatable
);
}
/**
* Get country flag emoji from country code.
* Converts 2-letter country code to Unicode regional indicator symbols.
*/
protected function countryFlag(): Attribute
{
return Attribute::make(
get: function (): ?string {
$countryCode = $this->getCountryFromIp()['countryCode'] ?? null;
if (empty($countryCode) || strlen($countryCode) !== 2) {
return null;
}
// Convert country code to regional indicator symbols (flag emoji)
// Each letter is converted to its regional indicator equivalent
// A = 🇦 (U+1F1E6), B = 🇧 (U+1F1E7), etc.
$countryCode = strtoupper($countryCode);
$flag = '';
for ($i = 0; $i < 2; $i++) {
$char = ord($countryCode[$i]) - ord('A') + 0x1F1E6;
$flag .= mb_chr($char, 'UTF-8');
}
return $flag;
},
);
}
/**
* Lookup country information from IP address using ip-api.com.
*
+1 -1
View File
@@ -266,7 +266,7 @@
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">{{ $user->host ?? 'N/A' }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
@if(!empty($user->country_code))
<span title="{{ $user->country_name }}">{{ $user->country_code }}</span>
<span title="{{ $user->country_name }}">{{ $user->country_flag }} {{ $user->country_code }}</span>
@else
N/A
@endif
+27
View File
@@ -101,4 +101,31 @@ final class UserCountryLookupTest extends TestCase
// Clean up
Cache::forget('ip_country_lookup_'.md5($ip));
}
public function test_country_flag_returns_emoji_flag(): void
{
// Set up a cache entry for US
$ip = '8.8.4.4';
$cacheKey = 'ip_country_lookup_'.md5($ip);
Cache::put($cacheKey, [
'country' => 'United States',
'countryCode' => 'US',
], 86400);
$user = new User;
$user->host = $ip;
$this->assertEquals('🇺🇸', $user->country_flag);
Cache::forget($cacheKey);
}
public function test_country_flag_returns_null_for_no_host(): void
{
$user = new User;
$user->host = null;
$this->assertNull($user->country_flag);
}
}