Passed
Push — master ( 1825c7...bd792e )
by
unknown
13:44 queued 15s
created

StringHelper::setCurrencyCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Shared;
4
5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
8
use Stringable;
9
10
class StringHelper
11
{
12
    /**
13
     * Control characters array.
14
     *
15
     * @var string[]
16
     */
17
    private static array $controlCharacters = [];
18
19
    /**
20
     * SYLK Characters array.
21
     *
22
     * @var string[]
23
     */
24
    private static array $SYLKCharacters = [];
25
26
    /**
27
     * Decimal separator.
28
     */
29
    private static ?string $decimalSeparator = null;
30
31
    /**
32
     * Thousands separator.
33
     */
34
    private static ?string $thousandsSeparator = null;
35
36
    /**
37
     * Currency code.
38
     */
39
    private static ?string $currencyCode = null;
40
41
    /**
42
     * Is iconv extension avalable?
43
     */
44
    private static ?bool $isIconvEnabled = null;
45
46
    /**
47
     * iconv options.
48
     */
49
    private static string $iconvOptions = '//IGNORE//TRANSLIT';
50
51
    /**
52
     * Build control characters array.
53
     */
54 112
    private static function buildControlCharacters(): void
55
    {
56 112
        for ($i = 0; $i <= 31; ++$i) {
57 112
            if ($i != 9 && $i != 10 && $i != 13) {
58 112
                $find = '_x' . sprintf('%04s', strtoupper(dechex($i))) . '_';
59 112
                $replace = chr($i);
60 112
                self::$controlCharacters[$find] = $replace;
61
            }
62
        }
63
    }
64
65
    /**
66
     * Build SYLK characters array.
67
     */
68 112
    private static function buildSYLKCharacters(): void
69
    {
70 112
        self::$SYLKCharacters = [
71 112
            "\x1B 0" => chr(0),
72 112
            "\x1B 1" => chr(1),
73 112
            "\x1B 2" => chr(2),
74 112
            "\x1B 3" => chr(3),
75 112
            "\x1B 4" => chr(4),
76 112
            "\x1B 5" => chr(5),
77 112
            "\x1B 6" => chr(6),
78 112
            "\x1B 7" => chr(7),
79 112
            "\x1B 8" => chr(8),
80 112
            "\x1B 9" => chr(9),
81 112
            "\x1B :" => chr(10),
82 112
            "\x1B ;" => chr(11),
83 112
            "\x1B <" => chr(12),
84 112
            "\x1B =" => chr(13),
85 112
            "\x1B >" => chr(14),
86 112
            "\x1B ?" => chr(15),
87 112
            "\x1B!0" => chr(16),
88 112
            "\x1B!1" => chr(17),
89 112
            "\x1B!2" => chr(18),
90 112
            "\x1B!3" => chr(19),
91 112
            "\x1B!4" => chr(20),
92 112
            "\x1B!5" => chr(21),
93 112
            "\x1B!6" => chr(22),
94 112
            "\x1B!7" => chr(23),
95 112
            "\x1B!8" => chr(24),
96 112
            "\x1B!9" => chr(25),
97 112
            "\x1B!:" => chr(26),
98 112
            "\x1B!;" => chr(27),
99 112
            "\x1B!<" => chr(28),
100 112
            "\x1B!=" => chr(29),
101 112
            "\x1B!>" => chr(30),
102 112
            "\x1B!?" => chr(31),
103 112
            "\x1B'?" => chr(127),
104 112
            "\x1B(0" => '€', // 128 in CP1252
105 112
            "\x1B(2" => '‚', // 130 in CP1252
106 112
            "\x1B(3" => 'ƒ', // 131 in CP1252
107 112
            "\x1B(4" => '„', // 132 in CP1252
108 112
            "\x1B(5" => '…', // 133 in CP1252
109 112
            "\x1B(6" => '†', // 134 in CP1252
110 112
            "\x1B(7" => '‡', // 135 in CP1252
111 112
            "\x1B(8" => 'ˆ', // 136 in CP1252
112 112
            "\x1B(9" => '‰', // 137 in CP1252
113 112
            "\x1B(:" => 'Š', // 138 in CP1252
114 112
            "\x1B(;" => '‹', // 139 in CP1252
115 112
            "\x1BNj" => 'Œ', // 140 in CP1252
116 112
            "\x1B(>" => 'Ž', // 142 in CP1252
117 112
            "\x1B)1" => '‘', // 145 in CP1252
118 112
            "\x1B)2" => '’', // 146 in CP1252
119 112
            "\x1B)3" => '“', // 147 in CP1252
120 112
            "\x1B)4" => '”', // 148 in CP1252
121 112
            "\x1B)5" => '•', // 149 in CP1252
122 112
            "\x1B)6" => '–', // 150 in CP1252
123 112
            "\x1B)7" => '—', // 151 in CP1252
124 112
            "\x1B)8" => '˜', // 152 in CP1252
125 112
            "\x1B)9" => '™', // 153 in CP1252
126 112
            "\x1B):" => 'š', // 154 in CP1252
127 112
            "\x1B);" => '›', // 155 in CP1252
128 112
            "\x1BNz" => 'œ', // 156 in CP1252
129 112
            "\x1B)>" => 'ž', // 158 in CP1252
130 112
            "\x1B)?" => 'Ÿ', // 159 in CP1252
131 112
            "\x1B*0" => ' ', // 160 in CP1252
132 112
            "\x1BN!" => '¡', // 161 in CP1252
133 112
            "\x1BN\"" => '¢', // 162 in CP1252
134 112
            "\x1BN#" => '£', // 163 in CP1252
135 112
            "\x1BN(" => '¤', // 164 in CP1252
136 112
            "\x1BN%" => '¥', // 165 in CP1252
137 112
            "\x1B*6" => '¦', // 166 in CP1252
138 112
            "\x1BN'" => '§', // 167 in CP1252
139 112
            "\x1BNH " => '¨', // 168 in CP1252
140 112
            "\x1BNS" => '©', // 169 in CP1252
141 112
            "\x1BNc" => 'ª', // 170 in CP1252
142 112
            "\x1BN+" => '«', // 171 in CP1252
143 112
            "\x1B*<" => '¬', // 172 in CP1252
144 112
            "\x1B*=" => '­', // 173 in CP1252
145 112
            "\x1BNR" => '®', // 174 in CP1252
146 112
            "\x1B*?" => '¯', // 175 in CP1252
147 112
            "\x1BN0" => '°', // 176 in CP1252
148 112
            "\x1BN1" => '±', // 177 in CP1252
149 112
            "\x1BN2" => '²', // 178 in CP1252
150 112
            "\x1BN3" => '³', // 179 in CP1252
151 112
            "\x1BNB " => '´', // 180 in CP1252
152 112
            "\x1BN5" => 'µ', // 181 in CP1252
153 112
            "\x1BN6" => '¶', // 182 in CP1252
154 112
            "\x1BN7" => '·', // 183 in CP1252
155 112
            "\x1B+8" => '¸', // 184 in CP1252
156 112
            "\x1BNQ" => '¹', // 185 in CP1252
157 112
            "\x1BNk" => 'º', // 186 in CP1252
158 112
            "\x1BN;" => '»', // 187 in CP1252
159 112
            "\x1BN<" => '¼', // 188 in CP1252
160 112
            "\x1BN=" => '½', // 189 in CP1252
161 112
            "\x1BN>" => '¾', // 190 in CP1252
162 112
            "\x1BN?" => '¿', // 191 in CP1252
163 112
            "\x1BNAA" => 'À', // 192 in CP1252
164 112
            "\x1BNBA" => 'Á', // 193 in CP1252
165 112
            "\x1BNCA" => 'Â', // 194 in CP1252
166 112
            "\x1BNDA" => 'Ã', // 195 in CP1252
167 112
            "\x1BNHA" => 'Ä', // 196 in CP1252
168 112
            "\x1BNJA" => 'Å', // 197 in CP1252
169 112
            "\x1BNa" => 'Æ', // 198 in CP1252
170 112
            "\x1BNKC" => 'Ç', // 199 in CP1252
171 112
            "\x1BNAE" => 'È', // 200 in CP1252
172 112
            "\x1BNBE" => 'É', // 201 in CP1252
173 112
            "\x1BNCE" => 'Ê', // 202 in CP1252
174 112
            "\x1BNHE" => 'Ë', // 203 in CP1252
175 112
            "\x1BNAI" => 'Ì', // 204 in CP1252
176 112
            "\x1BNBI" => 'Í', // 205 in CP1252
177 112
            "\x1BNCI" => 'Î', // 206 in CP1252
178 112
            "\x1BNHI" => 'Ï', // 207 in CP1252
179 112
            "\x1BNb" => 'Ð', // 208 in CP1252
180 112
            "\x1BNDN" => 'Ñ', // 209 in CP1252
181 112
            "\x1BNAO" => 'Ò', // 210 in CP1252
182 112
            "\x1BNBO" => 'Ó', // 211 in CP1252
183 112
            "\x1BNCO" => 'Ô', // 212 in CP1252
184 112
            "\x1BNDO" => 'Õ', // 213 in CP1252
185 112
            "\x1BNHO" => 'Ö', // 214 in CP1252
186 112
            "\x1B-7" => '×', // 215 in CP1252
187 112
            "\x1BNi" => 'Ø', // 216 in CP1252
188 112
            "\x1BNAU" => 'Ù', // 217 in CP1252
189 112
            "\x1BNBU" => 'Ú', // 218 in CP1252
190 112
            "\x1BNCU" => 'Û', // 219 in CP1252
191 112
            "\x1BNHU" => 'Ü', // 220 in CP1252
192 112
            "\x1B-=" => 'Ý', // 221 in CP1252
193 112
            "\x1BNl" => 'Þ', // 222 in CP1252
194 112
            "\x1BN{" => 'ß', // 223 in CP1252
195 112
            "\x1BNAa" => 'à', // 224 in CP1252
196 112
            "\x1BNBa" => 'á', // 225 in CP1252
197 112
            "\x1BNCa" => 'â', // 226 in CP1252
198 112
            "\x1BNDa" => 'ã', // 227 in CP1252
199 112
            "\x1BNHa" => 'ä', // 228 in CP1252
200 112
            "\x1BNJa" => 'å', // 229 in CP1252
201 112
            "\x1BNq" => 'æ', // 230 in CP1252
202 112
            "\x1BNKc" => 'ç', // 231 in CP1252
203 112
            "\x1BNAe" => 'è', // 232 in CP1252
204 112
            "\x1BNBe" => 'é', // 233 in CP1252
205 112
            "\x1BNCe" => 'ê', // 234 in CP1252
206 112
            "\x1BNHe" => 'ë', // 235 in CP1252
207 112
            "\x1BNAi" => 'ì', // 236 in CP1252
208 112
            "\x1BNBi" => 'í', // 237 in CP1252
209 112
            "\x1BNCi" => 'î', // 238 in CP1252
210 112
            "\x1BNHi" => 'ï', // 239 in CP1252
211 112
            "\x1BNs" => 'ð', // 240 in CP1252
212 112
            "\x1BNDn" => 'ñ', // 241 in CP1252
213 112
            "\x1BNAo" => 'ò', // 242 in CP1252
214 112
            "\x1BNBo" => 'ó', // 243 in CP1252
215 112
            "\x1BNCo" => 'ô', // 244 in CP1252
216 112
            "\x1BNDo" => 'õ', // 245 in CP1252
217 112
            "\x1BNHo" => 'ö', // 246 in CP1252
218 112
            "\x1B/7" => '÷', // 247 in CP1252
219 112
            "\x1BNy" => 'ø', // 248 in CP1252
220 112
            "\x1BNAu" => 'ù', // 249 in CP1252
221 112
            "\x1BNBu" => 'ú', // 250 in CP1252
222 112
            "\x1BNCu" => 'û', // 251 in CP1252
223 112
            "\x1BNHu" => 'ü', // 252 in CP1252
224 112
            "\x1B/=" => 'ý', // 253 in CP1252
225 112
            "\x1BN|" => 'þ', // 254 in CP1252
226 112
            "\x1BNHy" => 'ÿ', // 255 in CP1252
227 112
        ];
228
    }
229
230
    /**
231
     * Get whether iconv extension is available.
232
     */
233 230
    public static function getIsIconvEnabled(): bool
234
    {
235 230
        if (isset(self::$isIconvEnabled)) {
236 230
            return self::$isIconvEnabled;
237
        }
238
239
        // Assume no problems with iconv
240 75
        self::$isIconvEnabled = true;
241
242
        // Fail if iconv doesn't exist
243 75
        if (!function_exists('iconv')) {
244
            self::$isIconvEnabled = false;
245 75
        } elseif (!@iconv('UTF-8', 'UTF-16LE', 'x')) {
246
            // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false,
247
            self::$isIconvEnabled = false;
248 75
        } elseif (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
249
            // CUSTOM: IBM AIX iconv() does not work
250
            self::$isIconvEnabled = false;
251
        }
252
253
        // Deactivate iconv default options if they fail (as seen on IMB i)
254 75
        if (self::$isIconvEnabled && !@iconv('UTF-8', 'UTF-16LE' . self::$iconvOptions, 'x')) {
255
            self::$iconvOptions = '';
256
        }
257
258 75
        return self::$isIconvEnabled;
259
    }
260
261 639
    private static function buildCharacterSets(): void
262
    {
263 639
        if (empty(self::$controlCharacters)) {
264 112
            self::buildControlCharacters();
265
        }
266
267 639
        if (empty(self::$SYLKCharacters)) {
268 112
            self::buildSYLKCharacters();
269
        }
270
    }
271
272
    /**
273
     * Convert from OpenXML escaped control character to PHP control character.
274
     *
275
     * Excel 2007 team:
276
     * ----------------
277
     * That's correct, control characters are stored directly in the shared-strings table.
278
     * We do encode characters that cannot be represented in XML using the following escape sequence:
279
     * _xHHHH_ where H represents a hexadecimal character in the character's value...
280
     * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
281
     * element or in the shared string <t> element.
282
     *
283
     * @param string $textValue Value to unescape
284
     */
285 511
    public static function controlCharacterOOXML2PHP(string $textValue): string
286
    {
287 511
        self::buildCharacterSets();
288
289 511
        return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $textValue);
290
    }
291
292
    /**
293
     * Convert from PHP control character to OpenXML escaped control character.
294
     *
295
     * Excel 2007 team:
296
     * ----------------
297
     * That's correct, control characters are stored directly in the shared-strings table.
298
     * We do encode characters that cannot be represented in XML using the following escape sequence:
299
     * _xHHHH_ where H represents a hexadecimal character in the character's value...
300
     * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
301
     * element or in the shared string <t> element.
302
     *
303
     * @param string $textValue Value to escape
304
     */
305 270
    public static function controlCharacterPHP2OOXML(string $textValue): string
306
    {
307 270
        self::buildCharacterSets();
308
309 270
        return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $textValue);
310
    }
311
312
    /**
313
     * Try to sanitize UTF8, replacing invalid sequences with Unicode substitution characters.
314
     */
315 9112
    public static function sanitizeUTF8(string $textValue): string
316
    {
317 9112
        $textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue);
318 9112
        $subst = mb_substitute_character(); // default is question mark
319 9112
        mb_substitute_character(65533); // Unicode substitution character
320 9112
        $returnValue = (string) mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
321 9112
        mb_substitute_character($subst);
322
323 9112
        return $returnValue;
324
    }
325
326
    /**
327
     * Check if a string contains UTF8 data.
328
     */
329 1
    public static function isUTF8(string $textValue): bool
330
    {
331 1
        return $textValue === self::sanitizeUTF8($textValue);
332
    }
333
334
    /**
335
     * Formats a numeric value as a string for output in various output writers forcing
336
     * point as decimal separator in case locale is other than English.
337
     */
338 957
    public static function formatNumber(float|int|string|null $numericValue): string
339
    {
340 957
        if (is_float($numericValue)) {
341 957
            return str_replace(',', '.', (string) $numericValue);
342
        }
343
344 96
        return (string) $numericValue;
345
    }
346
347
    /**
348
     * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length)
349
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
350
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
351
     * although this will give wrong results for non-ASCII strings
352
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
353
     *
354
     * @param string $textValue UTF-8 encoded string
355
     * @param array<int, array{strlen: int, fontidx: int}> $arrcRuns Details of rich text runs in $value
356
     */
357 116
    public static function UTF8toBIFF8UnicodeShort(string $textValue, array $arrcRuns = []): string
358
    {
359
        // character count
360 116
        $ln = self::countCharacters($textValue, 'UTF-8');
361
        // option flags
362 116
        if (empty($arrcRuns)) {
363 116
            $data = pack('CC', $ln, 0x0001);
364
            // characters
365 116
            $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
366
        } else {
367 11
            $data = pack('vC', $ln, 0x09);
368 11
            $data .= pack('v', count($arrcRuns));
369
            // characters
370 11
            $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
371 11
            foreach ($arrcRuns as $cRun) {
372 11
                $data .= pack('v', $cRun['strlen']);
373 11
                $data .= pack('v', $cRun['fontidx']);
374
            }
375
        }
376
377 116
        return $data;
378
    }
379
380
    /**
381
     * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length)
382
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
383
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
384
     * although this will give wrong results for non-ASCII strings
385
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
386
     *
387
     * @param string $textValue UTF-8 encoded string
388
     */
389 117
    public static function UTF8toBIFF8UnicodeLong(string $textValue): string
390
    {
391
        // characters
392 117
        $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
393 117
        $ln = (int) (strlen($chars) / 2);  // N.B. - strlen, not mb_strlen issue #642
394
395 117
        return pack('vC', $ln, 0x0001) . $chars;
396
    }
397
398
    /**
399
     * Convert string from one encoding to another.
400
     *
401
     * @param string $to Encoding to convert to, e.g. 'UTF-8'
402
     * @param string $from Encoding to convert from, e.g. 'UTF-16LE'
403
     */
404 229
    public static function convertEncoding(string $textValue, string $to, string $from): string
405
    {
406 229
        if (self::getIsIconvEnabled()) {
407 229
            $result = iconv($from, $to . self::$iconvOptions, $textValue);
408 229
            if (false !== $result) {
409 229
                return $result;
410
            }
411
        }
412
413
        return (string) mb_convert_encoding($textValue, $to, $from);
414
    }
415
416
    /**
417
     * Get character count.
418
     *
419
     * @param string $encoding Encoding
420
     *
421
     * @return int Character count
422
     */
423 10611
    public static function countCharacters(string $textValue, string $encoding = 'UTF-8'): int
424
    {
425 10611
        return mb_strlen($textValue, $encoding);
426
    }
427
428
    /**
429
     * Get character count using mb_strwidth rather than mb_strlen.
430
     *
431
     * @param string $encoding Encoding
432
     *
433
     * @return int Character count
434
     */
435 79
    public static function countCharactersDbcs(string $textValue, string $encoding = 'UTF-8'): int
436
    {
437 79
        return mb_strwidth($textValue, $encoding);
438
    }
439
440
    /**
441
     * Get a substring of a UTF-8 encoded string.
442
     *
443
     * @param string $textValue UTF-8 encoded string
444
     * @param int $offset Start offset
445
     * @param ?int $length Maximum number of characters in substring
446
     */
447 10583
    public static function substring(string $textValue, int $offset, ?int $length = 0): string
448
    {
449 10583
        return mb_substr($textValue, $offset, $length, 'UTF-8');
450
    }
451
452
    /**
453
     * Convert a UTF-8 encoded string to upper case.
454
     *
455
     * @param string $textValue UTF-8 encoded string
456
     */
457 10385
    public static function strToUpper(string $textValue): string
458
    {
459 10385
        return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8');
460
    }
461
462
    /**
463
     * Convert a UTF-8 encoded string to lower case.
464
     *
465
     * @param string $textValue UTF-8 encoded string
466
     */
467 10133
    public static function strToLower(string $textValue): string
468
    {
469 10133
        return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8');
470
    }
471
472
    /**
473
     * Convert a UTF-8 encoded string to title/proper case
474
     * (uppercase every first character in each word, lower case all other characters).
475
     *
476
     * @param string $textValue UTF-8 encoded string
477
     */
478 18
    public static function strToTitle(string $textValue): string
479
    {
480 18
        return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
481
    }
482
483 21
    public static function mbIsUpper(string $character): bool
484
    {
485 21
        return mb_strtolower($character, 'UTF-8') !== $character;
486
    }
487
488
    /**
489
     * Splits a UTF-8 string into an array of individual characters.
490
     *
491
     * @return string[]
492
     */
493 21
    public static function mbStrSplit(string $string): array
494
    {
495
        // Split at all position not after the start: ^
496
        // and not before the end: $
497 21
        $split = Preg::split('/(?<!^)(?!$)/u', $string);
498
499 21
        return $split;
500
    }
501
502
    /**
503
     * Reverse the case of a string, so that all uppercase characters become lowercase
504
     * and all lowercase characters become uppercase.
505
     *
506
     * @param string $textValue UTF-8 encoded string
507
     */
508 21
    public static function strCaseReverse(string $textValue): string
509
    {
510 21
        $characters = self::mbStrSplit($textValue);
511 21
        foreach ($characters as &$character) {
512 21
            if (self::mbIsUpper($character)) {
513 14
                $character = mb_strtolower($character, 'UTF-8');
514
            } else {
515 17
                $character = mb_strtoupper($character, 'UTF-8');
516
            }
517
        }
518
519 21
        return implode('', $characters);
520
    }
521
522 1
    private static function useAlt(string $altValue, string $default, bool $trimAlt): string
523
    {
524 1
        return ($trimAlt ? trim($altValue) : $altValue) ?: $default;
525
    }
526
527 145
    private static function getLocaleValue(string $key, string $altKey, string $default, bool $trimAlt = false): string
528
    {
529
        /** @var string[] */
530 145
        $localeconv = localeconv();
531 145
        $rslt = $localeconv[$key];
532
        // win-1252 implements Euro as 0x80 plus other symbols
533
        // Not suitable for Composer\Pcre\Preg
534 145
        if (preg_match('//u', $rslt) !== 1) {
535 1
            $rslt = '';
536
        }
537
538 145
        return $rslt ?: self::useAlt($localeconv[$altKey], $default, $trimAlt);
539
    }
540
541
    /**
542
     * Get the decimal separator. If it has not yet been set explicitly, try to obtain number
543
     * formatting information from locale.
544
     */
545 1120
    public static function getDecimalSeparator(): string
546
    {
547 1120
        if (!isset(self::$decimalSeparator)) {
548 133
            self::$decimalSeparator = self::getLocaleValue('decimal_point', 'mon_decimal_point', '.');
549
        }
550
551 1120
        return self::$decimalSeparator;
552
    }
553
554
    /**
555
     * Set the decimal separator. Only used by NumberFormat::toFormattedString()
556
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
557
     *
558
     * @param ?string $separator Character for decimal separator
559
     */
560 927
    public static function setDecimalSeparator(?string $separator): void
561
    {
562 927
        self::$decimalSeparator = $separator;
563
    }
564
565
    /**
566
     * Get the thousands separator. If it has not yet been set explicitly, try to obtain number
567
     * formatting information from locale.
568
     */
569 1132
    public static function getThousandsSeparator(): string
570
    {
571 1132
        if (!isset(self::$thousandsSeparator)) {
572 134
            self::$thousandsSeparator = self::getLocaleValue('thousands_sep', 'mon_thousands_sep', ',');
573
        }
574
575 1132
        return self::$thousandsSeparator;
576
    }
577
578
    /**
579
     * Set the thousands separator. Only used by NumberFormat::toFormattedString()
580
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
581
     *
582
     * @param ?string $separator Character for thousands separator
583
     */
584 927
    public static function setThousandsSeparator(?string $separator): void
585
    {
586 927
        self::$thousandsSeparator = $separator;
587
    }
588
589
    /**
590
     *    Get the currency code. If it has not yet been set explicitly, try to obtain the
591
     *        symbol information from locale.
592
     */
593 78
    public static function getCurrencyCode(bool $trimAlt = false): string
594
    {
595 78
        if (!isset(self::$currencyCode)) {
596 28
            self::$currencyCode = self::getLocaleValue('currency_symbol', 'int_curr_symbol', '$', $trimAlt);
597
        }
598
599 78
        return self::$currencyCode;
600
    }
601
602
    /**
603
     * Set the currency code. Only used by NumberFormat::toFormattedString()
604
     *        to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
605
     *
606
     * @param ?string $currencyCode Character for currency code
607
     */
608 925
    public static function setCurrencyCode(?string $currencyCode): void
609
    {
610 925
        self::$currencyCode = $currencyCode;
611
    }
612
613
    /**
614
     * Convert SYLK encoded string to UTF-8.
615
     *
616
     * @param string $textValue SYLK encoded string
617
     *
618
     * @return string UTF-8 encoded string
619
     */
620 11
    public static function SYLKtoUTF8(string $textValue): string
621
    {
622 11
        self::buildCharacterSets();
623
624
        // If there is no escape character in the string there is nothing to do
625 11
        if (!str_contains($textValue, '')) {
626 10
            return $textValue;
627
        }
628
629 3
        foreach (self::$SYLKCharacters as $k => $v) {
630 3
            $textValue = str_replace($k, $v, $textValue);
631
        }
632
633 3
        return $textValue;
634
    }
635
636
    /**
637
     * Retrieve any leading numeric part of a string, or return the full string if no leading numeric
638
     * (handles basic integer or float, but not exponent or non decimal).
639
     *
640
     * @return float|string string or only the leading numeric part of the string
641
     */
642 299
    public static function testStringAsNumeric(string $textValue): float|string
643
    {
644 299
        if (is_numeric($textValue)) {
645 296
            return $textValue;
646
        }
647 6
        $v = (float) $textValue;
648
649 6
        return (is_numeric(substr($textValue, 0, strlen((string) $v)))) ? $v : $textValue;
650
    }
651
652 39
    public static function strlenAllowNull(?string $string): int
653
    {
654 39
        return strlen("$string");
655
    }
656
657
    /** @param bool $convertBool If true, convert bool to locale-aware TRUE/FALSE rather than 1/null-string */
658 14211
    public static function convertToString(mixed $value, bool $throw = true, string $default = '', bool $convertBool = false): string
659
    {
660 14211
        if ($convertBool && is_bool($value)) {
661 1
            return $value ? Calculation::getTRUE() : Calculation::getFALSE();
662
        }
663 14211
        if (is_float($value)) {
664 4685
            $string = (string) $value;
665
            // look out for scientific notation
666 4685
            if (!Preg::isMatch('/[^-+0-9.]/', $string)) {
667 4658
                $minus = $value < 0 ? '-' : '';
668 4658
                $positive = abs($value);
669 4658
                $floor = floor($positive);
670 4658
                $oldFrac = (string) ($positive - $floor);
671 4658
                $frac = Preg::replace('/^0[.](\d+)$/', '$1', $oldFrac);
672 4658
                if ($frac !== $oldFrac) {
673 4491
                    return "$minus$floor.$frac";
674
                }
675
            }
676
677 415
            return $string;
678
        }
679 14207
        if ($value === null || is_scalar($value) || $value instanceof Stringable) {
680 14203
            return (string) $value;
681
        }
682
683 5
        if ($throw) {
684 5
            throw new SpreadsheetException('Unable to convert to string');
685
        }
686
687 1
        return $default;
688
    }
689
690
    /**
691
     * Assist with POST items when samples are run in browser.
692
     * Never run as part of unit tests, which are command line.
693
     *
694
     * @codeCoverageIgnore
695
     */
696
    public static function convertPostToString(string $index, string $default = ''): string
697
    {
698
        if (isset($_POST[$index])) {
699
            return htmlentities(self::convertToString($_POST[$index], false, $default));
700
        }
701
702
        return $default;
703
    }
704
}
705