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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
 
namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;
 
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Stringable;
 
abstract class NumberBase implements Stringable
{
    protected const MAX_DECIMALS = 30;
 
    protected int $decimals = 2;
 
    protected ?string $locale = null;
 
    protected ?string $fullLocale = null;
 
    protected ?string $localeFormat = null;
 
    public function setDecimals(int $decimals = 2): void
    {
        $this->decimals = ($decimals > self::MAX_DECIMALS) ? self::MAX_DECIMALS : max($decimals, 0);
    }
 
    /**
     * Setting a locale will override any settings defined in this class.
     *
     * @throws Exception If the locale code is not a valid format
     */
    public function setLocale(?string $locale = null): void
    {
        if ($locale === null) {
            $this->localeFormat = $this->locale = $this->fullLocale = null;
 
            return;
        }
 
        $this->locale = $this->validateLocale($locale);
 
        if (class_exists(NumberFormatter::class)) {
            $this->localeFormat = $this->getLocaleFormat();
        }
    }
 
    /**
     * Stub: should be implemented as a concrete method in concrete wizards.
     */
    abstract protected function getLocaleFormat(): string;
 
    /**
     * @throws Exception If the locale code is not a valid format
     */
    private function validateLocale(string $locale): string
    {
        if (preg_match(Locale::STRUCTURE, $locale, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
            throw new Exception("Invalid locale code '{$locale}'");
        }
 
        ['language' => $language, 'script' => $script, 'country' => $country] = $matches;
        // Set case and separator to match standardised locale case
        $language = strtolower($language ?? '');
        $script = ($script === null) ? null : ucfirst(strtolower($script));
        $country = ($country === null) ? null : strtoupper($country);
 
        $this->fullLocale = implode('-', array_filter([$language, $script, $country]));
 
        return $country === null ? $language : "{$language}-{$country}";
    }
 
    public function format(): string
    {
        return NumberFormat::FORMAT_GENERAL;
    }
 
    public function __toString(): string
    {
        return $this->format();
    }
}