Files
CLOAK/lib/Cloak/CountryAllowlist.php
T

63 lines
1.7 KiB
PHP
Raw Normal View History

<?php
/**
* SHOW_SITE_COUNTRY 允许列表解析与比对
*/
require_once __DIR__ . '/CountryCodeNormalizer.php';
class CountryAllowlist
{
/**
* @param string $config 逗号分隔国家码,如 US,GB,CA
* @return string[]
*/
public static function parse($config)
{
2026-06-15 22:42:59 +08:00
$config = trim((string) $config);
if ($config === '') {
return [];
}
2026-06-15 22:42:59 +08:00
// 支持英文逗号、中文逗号、分号分隔
$parts = preg_split('/\s*[,;]\s*/u', $config);
$out = [];
foreach ($parts as $part) {
$part = trim($part);
2026-06-15 22:42:59 +08:00
if ($part === '') {
continue;
}
$normalized = CountryCodeNormalizer::toAlpha2($part);
if ($normalized !== null && $normalized !== '') {
$out[] = $normalized;
}
}
return array_values(array_unique($out));
}
2026-06-15 22:42:59 +08:00
/**
* 保存配置前规范化国家列表字符串(dashboard 写入用)
*
* @param string $config
* @return string 如 BR,CN
*/
public static function formatForConfig($config)
{
$list = self::parse($config);
return implode(',', $list);
}
/**
* @param string|null $countryCode
* @param string[] $allowlist
*/
public static function isAllowed($countryCode, array $allowlist)
{
if ($allowlist === []) {
return true;
}
$normalized = CountryCodeNormalizer::toAlpha2($countryCode);
if ($normalized === null || $normalized === '') {
return false;
}
return in_array($normalized, $allowlist, true);
}
}