Passed
Push — master ( 68fd71...055281 )
by
unknown
16:29 queued 06:03
created

StringHelper   F

Complexity

Total Complexity 81

Size/Duplication

Total Lines 694
Duplicated Lines 0 %

Test Coverage

Coverage 98.37%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 81
eloc 286
c 1
b 0
f 0
dl 0
loc 694
ccs 302
cts 307
cp 0.9837
rs 2

34 Methods

Rating   Name   Duplication   Size   Complexity  
A convertPostToString() 0 7 2
B buildSYLKCharacters() 0 159 1
A setDecimalSeparator() 0 3 1
A strToUpper() 0 3 1
A setCurrencyCode() 0 3 1
A getLocaleValue() 0 12 3
A controlCharacterOOXML2PHP() 0 5 1
C convertToString() 0 30 12
A UTF8toBIFF8UnicodeShort() 0 21 3
A countCharacters() 0 3 1
C getIsIconvEnabled() 0 26 12
A substring() 0 3 1
A strlenAllowNull() 0 3 1
A mbStrSplit() 0 7 1
A getThousandsSeparator() 0 7 2
A testStringAsNumeric() 0 8 3
A controlCharacterPHP2OOXML() 0 5 1
A SYLKtoUTF8() 0 14 3
A strCaseReverse() 0 12 3
A setThousandsSeparator() 0 3 1
A sanitizeUTF8() 0 10 1
A formatNumber() 0 7 2
A countCharactersDbcs() 0 3 1
A strToLower() 0 3 1
A UTF8toBIFF8UnicodeLong() 0 7 1
A useAlt() 0 3 3
A getCurrencyCode() 0 7 2
A buildCharacterSets() 0 8 3
A strToTitle() 0 3 1
A convertEncoding() 0 10 3
A mbIsUpper() 0 3 1
A isUTF8() 0 3 1
A buildControlCharacters() 0 7 5
A getDecimalSeparator() 0 7 2

How to fix   Complexity   

Complex Class

Complex classes like StringHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use StringHelper, and based on these observations, apply Extract Interface, too.

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 9108
    public static function sanitizeUTF8(string $textValue): string
316
    {
317 9108
        $textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue);
318 9108
        $subst = mb_substitute_character(); // default is question mark
319 9108
        mb_substitute_character(65533); // Unicode substitution character
320
        // Phpstan does not think this can return false.
321 9108
        $returnValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
322 9108
        mb_substitute_character($subst);
323
324 9108
        return $returnValue;
325
    }
326
327
    /**
328
     * Check if a string contains UTF8 data.
329
     */
330 1
    public static function isUTF8(string $textValue): bool
331
    {
332 1
        return $textValue === self::sanitizeUTF8($textValue);
333
    }
334
335
    /**
336
     * Formats a numeric value as a string for output in various output writers forcing
337
     * point as decimal separator in case locale is other than English.
338
     */
339 957
    public static function formatNumber(float|int|string|null $numericValue): string
340
    {
341 957
        if (is_float($numericValue)) {
342 957
            return str_replace(',', '.', (string) $numericValue);
343
        }
344
345 96
        return (string) $numericValue;
346
    }
347
348
    /**
349
     * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length)
350
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
351
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
352
     * although this will give wrong results for non-ASCII strings
353
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
354
     *
355
     * @param string $textValue UTF-8 encoded string
356
     * @param array<int, array{strlen: int, fontidx: int}> $arrcRuns Details of rich text runs in $value
357
     */
358 116
    public static function UTF8toBIFF8UnicodeShort(string $textValue, array $arrcRuns = []): string
359
    {
360
        // character count
361 116
        $ln = self::countCharacters($textValue, 'UTF-8');
362
        // option flags
363 116
        if (empty($arrcRuns)) {
364 116
            $data = pack('CC', $ln, 0x0001);
365
            // characters
366 116
            $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
367
        } else {
368 11
            $data = pack('vC', $ln, 0x09);
369 11
            $data .= pack('v', count($arrcRuns));
370
            // characters
371 11
            $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
372 11
            foreach ($arrcRuns as $cRun) {
373 11
                $data .= pack('v', $cRun['strlen']);
374 11
                $data .= pack('v', $cRun['fontidx']);
375
            }
376
        }
377
378 116
        return $data;
379
    }
380
381
    /**
382
     * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length)
383
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
384
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
385
     * although this will give wrong results for non-ASCII strings
386
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
387
     *
388
     * @param string $textValue UTF-8 encoded string
389
     */
390 117
    public static function UTF8toBIFF8UnicodeLong(string $textValue): string
391
    {
392
        // characters
393 117
        $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
394 117
        $ln = (int) (strlen($chars) / 2);  // N.B. - strlen, not mb_strlen issue #642
395
396 117
        return pack('vC', $ln, 0x0001) . $chars;
397
    }
398
399
    /**
400
     * Convert string from one encoding to another.
401
     *
402
     * @param string $to Encoding to convert to, e.g. 'UTF-8'
403
     * @param string $from Encoding to convert from, e.g. 'UTF-16LE'
404
     */
405 229
    public static function convertEncoding(string $textValue, string $to, string $from): string
406
    {
407 229
        if (self::getIsIconvEnabled()) {
408 229
            $result = iconv($from, $to . self::$iconvOptions, $textValue);
409 229
            if (false !== $result) {
410 229
                return $result;
411
            }
412
        }
413
414
        return mb_convert_encoding($textValue, $to, $from);
415
    }
416
417
    /**
418
     * Get character count.
419
     *
420
     * @param string $encoding Encoding
421
     *
422
     * @return int Character count
423
     */
424 10607
    public static function countCharacters(string $textValue, string $encoding = 'UTF-8'): int
425
    {
426 10607
        return mb_strlen($textValue, $encoding);
427
    }
428
429
    /**
430
     * Get character count using mb_strwidth rather than mb_strlen.
431
     *
432
     * @param string $encoding Encoding
433
     *
434
     * @return int Character count
435
     */
436 79
    public static function countCharactersDbcs(string $textValue, string $encoding = 'UTF-8'): int
437
    {
438 79
        return mb_strwidth($textValue, $encoding);
439
    }
440
441
    /**
442
     * Get a substring of a UTF-8 encoded string.
443
     *
444
     * @param string $textValue UTF-8 encoded string
445
     * @param int $offset Start offset
446
     * @param ?int $length Maximum number of characters in substring
447
     */
448 10579
    public static function substring(string $textValue, int $offset, ?int $length = 0): string
449
    {
450 10579
        return mb_substr($textValue, $offset, $length, 'UTF-8');
451
    }
452
453
    /**
454
     * Convert a UTF-8 encoded string to upper case.
455
     *
456
     * @param string $textValue UTF-8 encoded string
457
     */
458 10381
    public static function strToUpper(string $textValue): string
459
    {
460 10381
        return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8');
461
    }
462
463
    /**
464
     * Convert a UTF-8 encoded string to lower case.
465
     *
466
     * @param string $textValue UTF-8 encoded string
467
     */
468 10129
    public static function strToLower(string $textValue): string
469
    {
470 10129
        return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8');
471
    }
472
473
    /**
474
     * Convert a UTF-8 encoded string to title/proper case
475
     * (uppercase every first character in each word, lower case all other characters).
476
     *
477
     * @param string $textValue UTF-8 encoded string
478
     */
479 18
    public static function strToTitle(string $textValue): string
480
    {
481 18
        return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
482
    }
483
484 21
    public static function mbIsUpper(string $character): bool
485
    {
486 21
        return mb_strtolower($character, 'UTF-8') !== $character;
487
    }
488
489
    /**
490
     * Splits a UTF-8 string into an array of individual characters.
491
     *
492
     * @return string[]
493
     */
494 21
    public static function mbStrSplit(string $string): array
495
    {
496
        // Split at all position not after the start: ^
497
        // and not before the end: $
498 21
        $split = Preg::split('/(?<!^)(?!$)/u', $string);
499
500 21
        return $split;
501
    }
502
503
    /**
504
     * Reverse the case of a string, so that all uppercase characters become lowercase
505
     * and all lowercase characters become uppercase.
506
     *
507
     * @param string $textValue UTF-8 encoded string
508
     */
509 21
    public static function strCaseReverse(string $textValue): string
510
    {
511 21
        $characters = self::mbStrSplit($textValue);
512 21
        foreach ($characters as &$character) {
513 21
            if (self::mbIsUpper($character)) {
514 14
                $character = mb_strtolower($character, 'UTF-8');
515
            } else {
516 17
                $character = mb_strtoupper($character, 'UTF-8');
517
            }
518
        }
519
520 21
        return implode('', $characters);
521
    }
522
523 1
    private static function useAlt(string $altValue, string $default, bool $trimAlt): string
524
    {
525 1
        return ($trimAlt ? trim($altValue) : $altValue) ?: $default;
526
    }
527
528 145
    private static function getLocaleValue(string $key, string $altKey, string $default, bool $trimAlt = false): string
529
    {
530
        /** @var string[] */
531 145
        $localeconv = localeconv();
532 145
        $rslt = $localeconv[$key];
533
        // win-1252 implements Euro as 0x80 plus other symbols
534
        // Not suitable for Composer\Pcre\Preg
535 145
        if (preg_match('//u', $rslt) !== 1) {
536 1
            $rslt = '';
537
        }
538
539 145
        return $rslt ?: self::useAlt($localeconv[$altKey], $default, $trimAlt);
540
    }
541
542
    /**
543
     * Get the decimal separator. If it has not yet been set explicitly, try to obtain number
544
     * formatting information from locale.
545
     */
546 1119
    public static function getDecimalSeparator(): string
547
    {
548 1119
        if (!isset(self::$decimalSeparator)) {
549 133
            self::$decimalSeparator = self::getLocaleValue('decimal_point', 'mon_decimal_point', '.');
550
        }
551
552 1119
        return self::$decimalSeparator;
553
    }
554
555
    /**
556
     * Set the decimal separator. Only used by NumberFormat::toFormattedString()
557
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
558
     *
559
     * @param ?string $separator Character for decimal separator
560
     */
561 927
    public static function setDecimalSeparator(?string $separator): void
562
    {
563 927
        self::$decimalSeparator = $separator;
564
    }
565
566
    /**
567
     * Get the thousands separator. If it has not yet been set explicitly, try to obtain number
568
     * formatting information from locale.
569
     */
570 1131
    public static function getThousandsSeparator(): string
571
    {
572 1131
        if (!isset(self::$thousandsSeparator)) {
573 134
            self::$thousandsSeparator = self::getLocaleValue('thousands_sep', 'mon_thousands_sep', ',');
574
        }
575
576 1131
        return self::$thousandsSeparator;
577
    }
578
579
    /**
580
     * Set the thousands separator. Only used by NumberFormat::toFormattedString()
581
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
582
     *
583
     * @param ?string $separator Character for thousands separator
584
     */
585 927
    public static function setThousandsSeparator(?string $separator): void
586
    {
587 927
        self::$thousandsSeparator = $separator;
588
    }
589
590
    /**
591
     *    Get the currency code. If it has not yet been set explicitly, try to obtain the
592
     *        symbol information from locale.
593
     */
594 78
    public static function getCurrencyCode(bool $trimAlt = false): string
595
    {
596 78
        if (!isset(self::$currencyCode)) {
597 28
            self::$currencyCode = self::getLocaleValue('currency_symbol', 'int_curr_symbol', '$', $trimAlt);
598
        }
599
600 78
        return self::$currencyCode;
601
    }
602
603
    /**
604
     * Set the currency code. Only used by NumberFormat::toFormattedString()
605
     *        to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
606
     *
607
     * @param ?string $currencyCode Character for currency code
608
     */
609 925
    public static function setCurrencyCode(?string $currencyCode): void
610
    {
611 925
        self::$currencyCode = $currencyCode;
612
    }
613
614
    /**
615
     * Convert SYLK encoded string to UTF-8.
616
     *
617
     * @param string $textValue SYLK encoded string
618
     *
619
     * @return string UTF-8 encoded string
620
     */
621 11
    public static function SYLKtoUTF8(string $textValue): string
622
    {
623 11
        self::buildCharacterSets();
624
625
        // If there is no escape character in the string there is nothing to do
626 11
        if (!str_contains($textValue, '')) {
627 10
            return $textValue;
628
        }
629
630 3
        foreach (self::$SYLKCharacters as $k => $v) {
631 3
            $textValue = str_replace($k, $v, $textValue);
632
        }
633
634 3
        return $textValue;
635
    }
636
637
    /**
638
     * Retrieve any leading numeric part of a string, or return the full string if no leading numeric
639
     * (handles basic integer or float, but not exponent or non decimal).
640
     *
641
     * @return float|string string or only the leading numeric part of the string
642
     */
643 299
    public static function testStringAsNumeric(string $textValue): float|string
644
    {
645 299
        if (is_numeric($textValue)) {
646 296
            return $textValue;
647
        }
648 6
        $v = (float) $textValue;
649
650 6
        return (is_numeric(substr($textValue, 0, strlen((string) $v)))) ? $v : $textValue;
651
    }
652
653 39
    public static function strlenAllowNull(?string $string): int
654
    {
655 39
        return strlen("$string");
656
    }
657
658
    /** @param bool $convertBool If true, convert bool to locale-aware TRUE/FALSE rather than 1/null-string */
659 14207
    public static function convertToString(mixed $value, bool $throw = true, string $default = '', bool $convertBool = false): string
660
    {
661 14207
        if ($convertBool && is_bool($value)) {
662 1
            return $value ? Calculation::getTRUE() : Calculation::getFALSE();
663
        }
664 14207
        if (is_float($value)) {
665 4684
            $string = (string) $value;
666
            // look out for scientific notation
667 4684
            if (!Preg::isMatch('/[^-+0-9.]/', $string)) {
668 4657
                $minus = $value < 0 ? '-' : '';
669 4657
                $positive = abs($value);
670 4657
                $floor = floor($positive);
671 4657
                $oldFrac = (string) ($positive - $floor);
672 4657
                $frac = Preg::replace('/^0[.](\d+)$/', '$1', $oldFrac);
673 4657
                if ($frac !== $oldFrac) {
674 4491
                    return "$minus$floor.$frac";
675
                }
676
            }
677
678 414
            return $string;
679
        }
680 14203
        if ($value === null || is_scalar($value) || $value instanceof Stringable) {
681 14199
            return (string) $value;
682
        }
683
684 5
        if ($throw) {
685 5
            throw new SpreadsheetException('Unable to convert to string');
686
        }
687
688 1
        return $default;
689
    }
690
691
    /**
692
     * Assist with POST items when samples are run in browser.
693
     * Never run as part of unit tests, which are command line.
694
     *
695
     * @codeCoverageIgnore
696
     */
697
    public static function convertPostToString(string $index, string $default = ''): string
698
    {
699
        if (isset($_POST[$index])) {
700
            return htmlentities(self::convertToString($_POST[$index], false, $default));
701
        }
702
703
        return $default;
704
    }
705
}
706