Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
 
3
namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;
4
 
5
use NumberFormatter;
6
use PhpOffice\PhpSpreadsheet\Exception;
7
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
8
use Stringable;
9
 
10
abstract class NumberBase implements Stringable
11
{
12
    protected const MAX_DECIMALS = 30;
13
 
14
    protected int $decimals = 2;
15
 
16
    protected ?string $locale = null;
17
 
18
    protected ?string $fullLocale = null;
19
 
20
    protected ?string $localeFormat = null;
21
 
22
    public function setDecimals(int $decimals = 2): void
23
    {
24
        $this->decimals = ($decimals > self::MAX_DECIMALS) ? self::MAX_DECIMALS : max($decimals, 0);
25
    }
26
 
27
    /**
28
     * Setting a locale will override any settings defined in this class.
29
     *
30
     * @throws Exception If the locale code is not a valid format
31
     */
32
    public function setLocale(?string $locale = null): void
33
    {
34
        if ($locale === null) {
35
            $this->localeFormat = $this->locale = $this->fullLocale = null;
36
 
37
            return;
38
        }
39
 
40
        $this->locale = $this->validateLocale($locale);
41
 
42
        if (class_exists(NumberFormatter::class)) {
43
            $this->localeFormat = $this->getLocaleFormat();
44
        }
45
    }
46
 
47
    /**
48
     * Stub: should be implemented as a concrete method in concrete wizards.
49
     */
50
    abstract protected function getLocaleFormat(): string;
51
 
52
    /**
53
     * @throws Exception If the locale code is not a valid format
54
     */
55
    private function validateLocale(string $locale): string
56
    {
57
        if (preg_match(Locale::STRUCTURE, $locale, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
58
            throw new Exception("Invalid locale code '{$locale}'");
59
        }
60
 
61
        ['language' => $language, 'script' => $script, 'country' => $country] = $matches;
62
        // Set case and separator to match standardised locale case
63
        $language = strtolower($language);
64
        $script = ($script === null) ? null : ucfirst(strtolower($script));
65
        $country = ($country === null) ? null : strtoupper($country);
66
 
67
        $this->fullLocale = implode('-', array_filter([$language, $script, $country]));
68
 
69
        return $country === null ? $language : "{$language}-{$country}";
70
    }
71
 
72
    public function format(): string
73
    {
74
        return NumberFormat::FORMAT_GENERAL;
75
    }
76
 
77
    public function __toString(): string
78
    {
79
        return $this->format();
80
    }
81
}