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