You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/LocaleCode.php

37 lines
1.1 KiB
PHP

<?php
namespace App\Services;
/** Canonicalizes the BCP-47 subset used by public locale selection. */
final class LocaleCode
{
public static function canonicalize($value): ?string
{
if (!is_string($value)) {
return null;
}
$locale = str_replace('_', '-', trim($value));
if (preg_match(
'/\A[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*\z/D',
$locale
) !== 1) {
return null;
}
$parts = explode('-', $locale);
$parts[0] = strtolower($parts[0]);
for ($index = 1; $index < count($parts); $index++) {
$part = $parts[$index];
if (strlen($part) === 4 && ctype_alpha($part)) {
$parts[$index] = ucfirst(strtolower($part));
} elseif ((strlen($part) === 2 && ctype_alpha($part))
|| (strlen($part) === 3 && ctype_digit($part))) {
$parts[$index] = strtoupper($part);
} else {
$parts[$index] = strtolower($part);
}
}
return implode('-', $parts);
}
}