Passed
Push — master ( 01a0ea...f9783c )
by Sergei
04:18 queued 01:48
created

StringHelper::substring()   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 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 4
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Strings;
6
7
use InvalidArgumentException;
8
9
use function array_slice;
10
use function count;
11
use function function_exists;
12
use function max;
13
use function mb_strlen;
14
use function mb_strtolower;
15
use function mb_strtoupper;
16
use function mb_substr;
17
use function preg_match;
18
use function preg_replace;
19
use function str_ends_with;
20
use function str_starts_with;
21
use function strlen;
22
23
/**
24
 * Provides static methods to work with strings.
25
 */
26
final class StringHelper
27
{
28
    public const DEFAULT_WHITESPACE_PATTERN = "\pC\pZ";
29
30
    /**
31
     * Returns the number of bytes in the given string.
32
     * This method ensures the string is treated as a byte array even if `mbstring.func_overload` is turned on
33
     * by using {@see mb_strlen()}.
34
     *
35
     * @param string|null $input The string being measured for length.
36
     *
37
     * @return int The number of bytes in the given string.
38
     */
39 2
    public static function byteLength(?string $input): int
40
    {
41 2
        return mb_strlen((string)$input, '8bit');
42
    }
43
44
    /**
45
     * Returns the portion of string specified by the start and length parameters.
46
     * This method ensures the string is treated as a byte array by using `mb_substr()`.
47
     *
48
     * @param string $input The input string. Must be one character or longer.
49
     * @param int $start The starting position.
50
     * @param int|null $length The desired portion length. If not specified or `null`, there will be
51
     * no limit on length i.e. the output will be until the end of the string.
52
     *
53
     * @return string The extracted part of string, or FALSE on failure or an empty string.
54
     *
55
     * @see https://www.php.net/manual/en/function.substr.php
56
     */
57 1
    public static function byteSubstring(string $input, int $start, int $length = null): string
58
    {
59 1
        return mb_substr($input, $start, $length ?? mb_strlen($input, '8bit'), '8bit');
60
    }
61
62
    /**
63
     * Returns the trailing name component of a path.
64
     * This method is similar to the php function `basename()` except that it will
65
     * treat both \ and / as directory separators, independent of the operating system.
66
     * This method was mainly created to work on php namespaces. When working with real
67
     * file paths, PHP's `basename()` should work fine for you.
68
     * Note: this method is not aware of the actual filesystem, or path components such as "..".
69
     *
70
     * @param string $path A path string.
71
     * @param string $suffix If the name component ends in suffix this will also be cut off.
72
     *
73
     * @return string The trailing name component of the given path.
74
     *
75
     * @see https://www.php.net/manual/en/function.basename.php
76
     */
77 1
    public static function baseName(string $path, string $suffix = ''): string
78
    {
79 1
        $length = mb_strlen($suffix);
80 1
        if ($length > 0 && mb_substr($path, -$length) === $suffix) {
81 1
            $path = mb_substr($path, 0, -$length);
82
        }
83 1
        $path = rtrim(str_replace('\\', '/', $path), '/\\');
84 1
        $position = mb_strrpos($path, '/');
85 1
        if ($position !== false) {
86 1
            return mb_substr($path, $position + 1);
87
        }
88
89 1
        return $path;
90
    }
91
92
    /**
93
     * Returns parent directory's path.
94
     * This method is similar to `dirname()` except that it will treat
95
     * both \ and / as directory separators, independent of the operating system.
96
     *
97
     * @param string $path A path string.
98
     *
99
     * @return string The parent directory's path.
100
     *
101
     * @see https://www.php.net/manual/en/function.basename.php
102
     */
103 1
    public static function directoryName(string $path): string
104
    {
105 1
        $position = mb_strrpos(str_replace('\\', '/', $path), '/');
106 1
        if ($position !== false) {
107 1
            return mb_substr($path, 0, $position);
108
        }
109
110 1
        return '';
111
    }
112
113
    /**
114
     * Get part of string.
115
     *
116
     * @param string $string To get substring from.
117
     * @param int $start Character to start at.
118
     * @param int|null $length Number of characters to get.
119
     * @param string $encoding The encoding to use, defaults to "UTF-8".
120
     *
121
     * @see https://php.net/manual/en/function.mb-substr.php
122
     */
123 15
    public static function substring(string $string, int $start, int $length = null, string $encoding = 'UTF-8'): string
124
    {
125 15
        return mb_substr($string, $start, $length, $encoding);
126
    }
127
128
    /**
129
     * Replace text within a portion of a string.
130
     *
131
     * @param string $string The input string.
132
     * @param string $replacement The replacement string.
133
     * @param int $start Position to begin replacing substring at.
134
     * If start is non-negative, the replacing will begin at the start'th offset into string.
135
     * If start is negative, the replacing will begin at the start'th character from the end of string.
136
     * @param int|null $length Length of the substring to be replaced.
137
     * If given and is positive, it represents the length of the portion of string which is to be replaced.
138
     * If it is negative, it represents the number of characters from the end of string at which to stop replacing.
139
     * If it is not given, then it will default to the length of the string; i.e. end the replacing at the end of string.
140
     * If length is zero then this function will have the effect of inserting replacement into string at the given start offset.
141
     * @param string $encoding The encoding to use, defaults to "UTF-8".
142
     */
143 9
    public static function replaceSubstring(string $string, string $replacement, int $start, ?int $length = null, string $encoding = 'UTF-8'): string
144
    {
145 9
        $stringLength = mb_strlen($string, $encoding);
146
147 9
        if ($start < 0) {
148 2
            $start = max(0, $stringLength + $start);
149 7
        } elseif ($start > $stringLength) {
150 1
            $start = $stringLength;
151
        }
152
153 9
        if ($length !== null && $length < 0) {
154 3
            $length = max(0, $stringLength - $start + $length);
155 6
        } elseif ($length === null || $length > $stringLength) {
156 5
            $length = $stringLength;
157
        }
158
159 9
        if (($start + $length) > $stringLength) {
160 4
            $length = $stringLength - $start;
161
        }
162
163 9
        return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $stringLength - $start - $length, $encoding);
164
    }
165
166
    /**
167
     * Check if given string starts with specified substring.
168
     * Binary and multibyte safe.
169
     *
170
     * @param string $input Input string.
171
     * @param string|null $with Part to search inside the $string.
172
     *
173
     * @return bool Returns true if first input starts with second input, false otherwise.
174
     */
175 19
    public static function startsWith(string $input, ?string $with): bool
176
    {
177 19
        if ($with === null) {
178 1
            return true;
179
        }
180
181 18
        if (function_exists('\str_starts_with')) {
182 18
            return str_starts_with($input, $with);
183
        }
184
185
        $bytes = self::byteLength($with);
186
        if ($bytes === 0) {
187
            return true;
188
        }
189
190
        return strncmp($input, $with, $bytes) === 0;
191
    }
192
193
    /**
194
     * Check if given string starts with specified substring ignoring case.
195
     * Binary and multibyte safe.
196
     *
197
     * @param string $input Input string.
198
     * @param string|null $with Part to search inside the $string.
199
     *
200
     * @return bool Returns true if first input starts with second input, false otherwise.
201
     */
202 1
    public static function startsWithIgnoringCase(string $input, ?string $with): bool
203
    {
204 1
        $bytes = self::byteLength($with);
205 1
        if ($bytes === 0) {
206 1
            return true;
207
        }
208
209
        /**
210
         * @psalm-suppress PossiblyNullArgument
211
         */
212 1
        return self::lowercase(self::substring($input, 0, $bytes, '8bit')) === self::lowercase($with);
0 ignored issues
show
Bug introduced by
It seems like $with can also be of type null; however, parameter $string of Yiisoft\Strings\StringHelper::lowercase() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

212
        return self::lowercase(self::substring($input, 0, $bytes, '8bit')) === self::lowercase(/** @scrutinizer ignore-type */ $with);
Loading history...
213
    }
214
215
    /**
216
     * Check if given string ends with specified substring.
217
     * Binary and multibyte safe.
218
     *
219
     * @param string $input Input string to check.
220
     * @param string|null $with Part to search inside of the $string.
221
     *
222
     * @return bool Returns true if first input ends with second input, false otherwise.
223
     */
224 19
    public static function endsWith(string $input, ?string $with): bool
225
    {
226 19
        if ($with === null) {
227 1
            return true;
228
        }
229
230 18
        if (function_exists('\str_ends_with')) {
231 18
            return str_ends_with($input, $with);
232
        }
233
234
        $bytes = self::byteLength($with);
235
        if ($bytes === 0) {
236
            return true;
237
        }
238
239
        // Warning check, see https://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
240
        if (self::byteLength($input) < $bytes) {
241
            return false;
242
        }
243
244
        return substr_compare($input, $with, -$bytes, $bytes) === 0;
245
    }
246
247
    /**
248
     * Check if given string ends with specified substring.
249
     * Binary and multibyte safe.
250
     *
251
     * @param string $input Input string to check.
252
     * @param string|null $with Part to search inside of the $string.
253
     *
254
     * @return bool Returns true if first input ends with second input, false otherwise.
255
     */
256 1
    public static function endsWithIgnoringCase(string $input, ?string $with): bool
257
    {
258 1
        $bytes = self::byteLength($with);
259 1
        if ($bytes === 0) {
260 1
            return true;
261
        }
262
263
        /**
264
         * @psalm-suppress PossiblyNullArgument
265
         */
266 1
        return self::lowercase(mb_substr($input, -$bytes, mb_strlen($input, '8bit'), '8bit')) === self::lowercase($with);
0 ignored issues
show
Bug introduced by
It seems like $with can also be of type null; however, parameter $string of Yiisoft\Strings\StringHelper::lowercase() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

266
        return self::lowercase(mb_substr($input, -$bytes, mb_strlen($input, '8bit'), '8bit')) === self::lowercase(/** @scrutinizer ignore-type */ $with);
Loading history...
267
    }
268
269
    /**
270
     * Truncates a string from the beginning to the number of characters specified.
271
     *
272
     * @param string $input String to process.
273
     * @param int $length Maximum length of the truncated string including trim marker.
274
     * @param string $trimMarker String to append to the beginning.
275
     * @param string $encoding The encoding to use, defaults to "UTF-8".
276
     */
277 1
    public static function truncateBegin(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
278
    {
279 1
        $inputLength = mb_strlen($input, $encoding);
280
281 1
        if ($inputLength <= $length) {
282 1
            return $input;
283
        }
284
285 1
        $trimMarkerLength = mb_strlen($trimMarker, $encoding);
286 1
        return self::replaceSubstring($input, $trimMarker, 0, -$length + $trimMarkerLength, $encoding);
287
    }
288
289
    /**
290
     * Truncates a string in the middle. Keeping start and end.
291
     * `StringHelper::truncateMiddle('Hello world number 2', 8)` produces "Hell…r 2".
292
     *
293
     * @param string $input The string to truncate.
294
     * @param int $length Maximum length of the truncated string including trim marker.
295
     * @param string $trimMarker String to append in the middle of truncated string.
296
     * @param string $encoding The encoding to use, defaults to "UTF-8".
297
     *
298
     * @return string The truncated string.
299
     */
300 2
    public static function truncateMiddle(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
301
    {
302 2
        $inputLength = mb_strlen($input, $encoding);
303
304 2
        if ($inputLength <= $length) {
305 1
            return $input;
306
        }
307
308 1
        $trimMarkerLength = mb_strlen($trimMarker, $encoding);
309 1
        $start = (int)ceil(($length - $trimMarkerLength) / 2);
310 1
        $end = $length - $start - $trimMarkerLength;
311
312 1
        return self::replaceSubstring($input, $trimMarker, $start, -$end, $encoding);
313
    }
314
315
    /**
316
     * Truncates a string from the end to the number of characters specified.
317
     *
318
     * @param string $input The string to truncate.
319
     * @param int $length Maximum length of the truncated string including trim marker.
320
     * @param string $trimMarker String to append to the end of truncated string.
321
     * @param string $encoding The encoding to use, defaults to "UTF-8".
322
     *
323
     * @return string The truncated string.
324
     */
325 1
    public static function truncateEnd(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
326
    {
327 1
        $inputLength = mb_strlen($input, $encoding);
328
329 1
        if ($inputLength <= $length) {
330 1
            return $input;
331
        }
332
333 1
        $trimMarkerLength = mb_strlen($trimMarker, $encoding);
334 1
        return rtrim(mb_substr($input, 0, $length - $trimMarkerLength, $encoding)) . $trimMarker;
335
    }
336
337
    /**
338
     * Truncates a string to the number of words specified.
339
     *
340
     * @param string $input The string to truncate.
341
     * @param int $count How many words from original string to include into truncated string.
342
     * @param string $trimMarker String to append to the end of truncated string.
343
     *
344
     * @return string The truncated string.
345
     */
346 1
    public static function truncateWords(string $input, int $count, string $trimMarker = '…'): string
347
    {
348
        /** @psalm-var list<string> $words */
349 1
        $words = preg_split('/(\s+)/u', trim($input), -1, PREG_SPLIT_DELIM_CAPTURE);
350 1
        if (count($words) / 2 > $count) {
351 1
            $words = array_slice($words, 0, ($count * 2) - 1);
352 1
            return implode('', $words) . $trimMarker;
353
        }
354
355 1
        return $input;
356
    }
357
358
    /**
359
     * Get string length.
360
     *
361
     * @param string $string String to calculate length for.
362
     * @param string $encoding The encoding to use, defaults to "UTF-8".
363
     *
364
     * @see https://php.net/manual/en/function.mb-strlen.php
365
     */
366 1
    public static function length(string $string, string $encoding = 'UTF-8'): int
367
    {
368 1
        return mb_strlen($string, $encoding);
369
    }
370
371
    /**
372
     * Counts words in a string.
373
     */
374 1
    public static function countWords(string $input): int
375
    {
376
        /** @var array $words */
377 1
        $words = preg_split('/\s+/u', $input, -1, PREG_SPLIT_NO_EMPTY);
378 1
        return count($words);
379
    }
380
381
    /**
382
     * Make a string lowercase.
383
     *
384
     * @param string $string String to process.
385
     * @param string $encoding The encoding to use, defaults to "UTF-8".
386
     *
387
     * @see https://php.net/manual/en/function.mb-strtolower.php
388
     */
389 3
    public static function lowercase(string $string, string $encoding = 'UTF-8'): string
390
    {
391 3
        return mb_strtolower($string, $encoding);
392
    }
393
394
    /**
395
     * Make a string uppercase.
396
     *
397
     * @param string $string String to process.
398
     * @param string $encoding The encoding to use, defaults to "UTF-8".
399
     *
400
     * @see https://php.net/manual/en/function.mb-strtoupper.php
401
     */
402 15
    public static function uppercase(string $string, string $encoding = 'UTF-8'): string
403
    {
404 15
        return mb_strtoupper($string, $encoding);
405
    }
406
407
    /**
408
     * Make a string's first character uppercase.
409
     *
410
     * @param string $string The string to be processed.
411
     * @param string $encoding The encoding to use, defaults to "UTF-8".
412
     *
413
     * @see https://php.net/manual/en/function.ucfirst.php
414
     */
415 14
    public static function uppercaseFirstCharacter(string $string, string $encoding = 'UTF-8'): string
416
    {
417 14
        $firstCharacter = self::substring($string, 0, 1, $encoding);
418 14
        $rest = self::substring($string, 1, null, $encoding);
419
420 14
        return self::uppercase($firstCharacter, $encoding) . $rest;
421
    }
422
423
    /**
424
     * Uppercase the first character of each word in a string.
425
     *
426
     * @param string $string The string to be processed.
427
     * @param string $encoding The encoding to use, defaults to "UTF-8".
428
     *
429
     * @see https://php.net/manual/en/function.ucwords.php
430
     */
431 10
    public static function uppercaseFirstCharacterInEachWord(string $string, string $encoding = 'UTF-8'): string
432
    {
433 10
        $words = preg_split('/\s/u', $string, -1, PREG_SPLIT_NO_EMPTY);
434
435 10
        $wordsWithUppercaseFirstCharacter = array_map(
436 10
            static function (string $word) use ($encoding) {
437 9
                return self::uppercaseFirstCharacter($word, $encoding);
438 10
            },
439 10
            $words
440 10
        );
441
442 10
        return implode(' ', $wordsWithUppercaseFirstCharacter);
443
    }
444
445
    /**
446
     * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
447
     *
448
     * > Note: Base 64 padding `=` may be at the end of the returned string.
449
     * > `=` is not transparent to URL encoding.
450
     *
451
     * @see https://tools.ietf.org/html/rfc4648#page-7
452
     *
453
     * @param string $input The string to encode.
454
     *
455
     * @return string Encoded string.
456
     */
457 4
    public static function base64UrlEncode(string $input): string
458
    {
459 4
        return strtr(base64_encode($input), '+/', '-_');
460
    }
461
462
    /**
463
     * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
464
     *
465
     * @see https://tools.ietf.org/html/rfc4648#page-7
466
     *
467
     * @param string $input Encoded string.
468
     *
469
     * @return string Decoded string.
470
     */
471 4
    public static function base64UrlDecode(string $input): string
472
    {
473 4
        return base64_decode(strtr($input, '-_', '+/'));
474
    }
475
476
    /**
477
     * Split a string to array with non-empty lines.
478
     * Whitespace from the beginning and end of a each line will be stripped.
479
     *
480
     * @param string $string The input string.
481
     * @param string $separator The boundary string. It is a part of regular expression
482
     * so should be taken into account or properly escaped with {@see preg_quote()}.
483
     */
484 16
    public static function split(string $string, string $separator = '\R'): array
485
    {
486 16
        $string = preg_replace('(^\s*|\s*$)', '', $string);
487 16
        return preg_split('~\s*' . $separator . '\s*~u', $string, -1, PREG_SPLIT_NO_EMPTY);
488
    }
489
490
    /**
491
     * @param string $path The path of where do you want to write a value to `$array`. The path can be described by
492
     * a string when each key should be separated by delimiter. If a path item contains delimiter, it can be escaped
493
     * with "\" (backslash) or a custom delimiter can be used.
494
     * @param string $delimiter A separator, used to parse string key for embedded object property retrieving. Defaults
495
     * to "." (dot).
496
     * @param string $escapeCharacter An escape character, used to escape delimiter. Defaults to "\" (backslash).
497
     * @param bool $preserveDelimiterEscaping Whether to preserve delimiter escaping in the items of final array (in
498
     * case of using string as an input). When `false`, "\" (backslashes) are removed. For a "." as delimiter, "."
499
     * becomes "\.". Defaults to `false`.
500
     *
501
     * @return string[]
502
     *
503
     * @psalm-return list<string>
504
     */
505 34
    public static function parsePath(
506
        string $path,
507
        string $delimiter = '.',
508
        string $escapeCharacter = '\\',
509
        bool $preserveDelimiterEscaping = false
510
    ): array {
511 34
        if (strlen($delimiter) !== 1) {
512 1
            throw new InvalidArgumentException('Only 1 character is allowed for delimiter.');
513
        }
514
515 33
        if (strlen($escapeCharacter) !== 1) {
516 1
            throw new InvalidArgumentException('Only 1 escape character is allowed.');
517
        }
518
519 32
        if ($delimiter === $escapeCharacter) {
520 1
            throw new InvalidArgumentException('Delimiter and escape character must be different.');
521
        }
522
523 31
        if ($path === '') {
524 2
            return [];
525
        }
526
527
        /** @psalm-var non-empty-list<array{0:string, 1:int}> $matches */
528 29
        $matches = preg_split(
529 29
            sprintf(
530 29
                '/(?<!%1$s)((?>%1$s%1$s)*)%2$s/',
531 29
                preg_quote($escapeCharacter, '/'),
532 29
                preg_quote($delimiter, '/')
533 29
            ),
534 29
            $path,
535 29
            -1,
536 29
            PREG_SPLIT_OFFSET_CAPTURE
537 29
        );
538 29
        $result = [];
539 29
        $countResults = count($matches);
540 29
        for ($i = 1; $i < $countResults; $i++) {
541 25
            $l = $matches[$i][1] - $matches[$i - 1][1] - strlen($matches[$i - 1][0]) - 1;
542 25
            $result[] = $matches[$i - 1][0] . ($l > 0 ? str_repeat($escapeCharacter, $l) : '');
543
        }
544 29
        $result[] = $matches[$countResults - 1][0];
545
546 29
        if ($preserveDelimiterEscaping === true) {
547 1
            return $result;
548
        }
549
550 28
        return array_map(
551 28
            static fn (string $key): string => str_replace(
552 28
                [
553 28
                    $escapeCharacter . $escapeCharacter,
554 28
                    $escapeCharacter . $delimiter,
555 28
                ],
556 28
                [
557 28
                    $escapeCharacter,
558 28
                    $delimiter,
559 28
                ],
560 28
                $key
561 28
            ),
562 28
            $result
563 28
        );
564
    }
565
566
    /**
567
     * Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning and end of a string.
568
     * Input string and pattern are treated as UTF-8.
569
     *
570
     * @see https://en.wikipedia.org/wiki/Whitespace_character#Unicode
571
     * @see https://www.php.net/manual/function.preg-replace
572
     *
573
     * @param string|string[] $string The string or an array with strings.
574
     * @param string $pattern PCRE regex pattern to search for, as UTF-8 string. Use {@see preg_quote()} to quote `$pattern` if it contains
575
     * special regular expression characters.
576
     *
577
     * @psalm-template TKey of array-key
578
     * @psalm-param string|array<TKey, string> $string
579
     * @psalm-param non-empty-string $pattern
580
     * @psalm-return ($string is array ? array<TKey, string> : string)
581
     *
582
     * @return string|string[]
583
     */
584 16
    public static function trim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
585
    {
586 16
        self::ensureUtf8Pattern($pattern);
587
588 15
        return preg_replace("#^[$pattern]+|[$pattern]+$#uD", '', $string);
589
    }
590
591
    /**
592
     * Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning of a string.
593
     *
594
     * @see self::trim()
595
     *
596
     * @param string|string[] $string The string or an array with strings.
597
     * @param string $pattern PCRE regex pattern to search for, as UTF-8 string. Use {@see preg_quote()} to quote `$pattern` if it contains
598
     * special regular expression characters.
599
     *
600
     * @psalm-template TKey of array-key
601
     * @psalm-param string|array<TKey, string> $string
602
     * @psalm-param non-empty-string $pattern
603
     * @psalm-return ($string is array ? array<TKey, string> : string)
604
     *
605
     * @return string|string[]
606
     */
607 12
    public static function ltrim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
608
    {
609 12
        self::ensureUtf8Pattern($pattern);
610
611 12
        return preg_replace("#^[$pattern]+#u", '', $string);
612
    }
613
614
    /**
615
     * Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the end of a string.
616
     *
617
     * @see self::trim()
618
     *
619
     * @param string|string[] $string The string or an array with strings.
620
     * @param string $pattern PCRE regex pattern to search for, as UTF-8 string. Use {@see preg_quote()} to quote `$pattern` if it contains
621
     * special regular expression characters.
622
     *
623
     * @psalm-template TKey of array-key
624
     * @psalm-param string|array<TKey, string> $string
625
     * @psalm-param non-empty-string $pattern
626
     * @psalm-return ($string is array ? array<TKey, string> : string)
627
     *
628
     * @return string|string[]
629
     */
630 14
    public static function rtrim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
631
    {
632 14
        self::ensureUtf8Pattern($pattern);
633
634 14
        return preg_replace("#[$pattern]+$#uD", '', $string);
635
    }
636
637
    /**
638
     * Ensure the input string is a valid UTF-8 string.
639
     *
640
     * @param string $pattern The input string.
641
     *
642
     * @throws InvalidArgumentException
643
     */
644 42
    private static function ensureUtf8Pattern(string $pattern): void
645
    {
646 42
        if (!preg_match('##u', $pattern)) {
647 1
            throw new InvalidArgumentException('Pattern is not a valid UTF-8 string.');
648
        }
649
    }
650
}
651