chengkun
2025-09-09 774d962b76d63366ed26c395e0a33cdbec309242
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
 
namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;
 
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
 
final class Locale
{
    /**
     * Language code: ISO-639 2 character, alpha.
     * Optional script code: ISO-15924 4 alpha.
     * Optional country code: ISO-3166-1, 2 character alpha.
     * Separated by underscores or dashes.
     */
    public const STRUCTURE = '/^(?P<language>[a-z]{2})([-_](?P<script>[a-z]{4}))?([-_](?P<country>[a-z]{2}))?$/i';
 
    private NumberFormatter $formatter;
 
    public function __construct(?string $locale, int $style)
    {
        if (class_exists(NumberFormatter::class) === false) {
            throw new Exception();
        }
 
        $formatterLocale = str_replace('-', '_', $locale ?? '');
        $this->formatter = new NumberFormatter($formatterLocale, $style);
        if ($this->formatter->getLocale() !== $formatterLocale) {
            throw new Exception("Unable to read locale data for '{$locale}'");
        }
    }
 
    public function format(bool $stripRlm = true): string
    {
        $str = $this->formatter->getPattern();
 
        return ($stripRlm && str_starts_with($str, "\xe2\x80\x8f")) ? substr($str, 3) : $str;
    }
}