Passed
Pull Request — master (#83)
by Sergei
02:24
created

StringHelper::directoryName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
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 1
        $words = preg_split('/(\s+)/u', trim($input), -1, PREG_SPLIT_DELIM_CAPTURE);
349 1
        if ((is_countable($words) ? count($words) : 0) / 2 > $count) {
350
            /** @var string[] $words */
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 1
        return is_countable(preg_split('/\s+/u', $input, -1, PREG_SPLIT_NO_EMPTY)) ? count(preg_split('/\s+/u', $input, -1, PREG_SPLIT_NO_EMPTY)) : 0;
377
    }
378
379
    /**
380
     * Make a string lowercase.
381
     *
382
     * @param string $string String to process.
383
     * @param string $encoding The encoding to use, defaults to "UTF-8".
384
     *
385
     * @see https://php.net/manual/en/function.mb-strtolower.php
386
     */
387 3
    public static function lowercase(string $string, string $encoding = 'UTF-8'): string
388
    {
389 3
        return mb_strtolower($string, $encoding);
390
    }
391
392
    /**
393
     * Make a string uppercase.
394
     *
395
     * @param string $string String to process.
396
     * @param string $encoding The encoding to use, defaults to "UTF-8".
397
     *
398
     * @see https://php.net/manual/en/function.mb-strtoupper.php
399
     */
400 15
    public static function uppercase(string $string, string $encoding = 'UTF-8'): string
401
    {
402 15
        return mb_strtoupper($string, $encoding);
403
    }
404
405
    /**
406
     * Make a string's first character uppercase.
407
     *
408
     * @param string $string The string to be processed.
409
     * @param string $encoding The encoding to use, defaults to "UTF-8".
410
     *
411
     * @see https://php.net/manual/en/function.ucfirst.php
412
     */
413 14
    public static function uppercaseFirstCharacter(string $string, string $encoding = 'UTF-8'): string
414
    {
415 14
        $firstCharacter = self::substring($string, 0, 1, $encoding);
416 14
        $rest = self::substring($string, 1, null, $encoding);
417
418 14
        return self::uppercase($firstCharacter, $encoding) . $rest;
419
    }
420
421
    /**
422
     * Uppercase the first character of each word in a string.
423
     *
424
     * @param string $string The string to be processed.
425
     * @param string $encoding The encoding to use, defaults to "UTF-8".
426
     *
427
     * @see https://php.net/manual/en/function.ucwords.php
428
     */
429 10
    public static function uppercaseFirstCharacterInEachWord(string $string, string $encoding = 'UTF-8'): string
430
    {
431 10
        $words = preg_split('/\s/u', $string, -1, PREG_SPLIT_NO_EMPTY);
432
433 10
        $wordsWithUppercaseFirstCharacter = array_map(static fn (string $word) => self::uppercaseFirstCharacter($word, $encoding), $words);
434
435 10
        return implode(' ', $wordsWithUppercaseFirstCharacter);
436
    }
437
438
    /**
439
     * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
440
     *
441
     * > Note: Base 64 padding `=` may be at the end of the returned string.
442
     * > `=` is not transparent to URL encoding.
443
     *
444
     * @see https://tools.ietf.org/html/rfc4648#page-7
445
     *
446
     * @param string $input The string to encode.
447
     *
448
     * @return string Encoded string.
449
     */
450 4
    public static function base64UrlEncode(string $input): string
451
    {
452 4
        return strtr(base64_encode($input), '+/', '-_');
453
    }
454
455
    /**
456
     * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
457
     *
458
     * @see https://tools.ietf.org/html/rfc4648#page-7
459
     *
460
     * @param string $input Encoded string.
461
     *
462
     * @return string Decoded string.
463
     */
464 4
    public static function base64UrlDecode(string $input): string
465
    {
466 4
        return base64_decode(strtr($input, '-_', '+/'));
467
    }
468
469
    /**
470
     * Split a string to array with non-empty lines.
471
     * Whitespace from the beginning and end of a each line will be stripped.
472
     *
473
     * @param string $string The input string.
474
     * @param string $separator The boundary string. It is a part of regular expression
475
     * so should be taken into account or properly escaped with {@see preg_quote()}.
476
     */
477 16
    public static function split(string $string, string $separator = '\R'): array
478
    {
479 16
        $string = preg_replace('(^\s*|\s*$)', '', $string);
480 16
        return preg_split('~\s*' . $separator . '\s*~u', $string, -1, PREG_SPLIT_NO_EMPTY);
481
    }
482
483
    /**
484
     * @param string $path The path of where do you want to write a value to `$array`. The path can be described by
485
     * a string when each key should be separated by delimiter. If a path item contains delimiter, it can be escaped
486
     * with "\" (backslash) or a custom delimiter can be used.
487
     * @param string $delimiter A separator, used to parse string key for embedded object property retrieving. Defaults
488
     * to "." (dot).
489
     * @param string $escapeCharacter An escape character, used to escape delimiter. Defaults to "\" (backslash).
490
     * @param bool $preserveDelimiterEscaping Whether to preserve delimiter escaping in the items of final array (in
491
     * case of using string as an input). When `false`, "\" (backslashes) are removed. For a "." as delimiter, "."
492
     * becomes "\.". Defaults to `false`.
493
     *
494
     * @return string[]
495
     *
496
     * @psalm-return list<string>
497
     */
498 34
    public static function parsePath(
499
        string $path,
500
        string $delimiter = '.',
501
        string $escapeCharacter = '\\',
502
        bool $preserveDelimiterEscaping = false
503
    ): array {
504 34
        if (strlen($delimiter) !== 1) {
505 1
            throw new InvalidArgumentException('Only 1 character is allowed for delimiter.');
506
        }
507
508 33
        if (strlen($escapeCharacter) !== 1) {
509 1
            throw new InvalidArgumentException('Only 1 escape character is allowed.');
510
        }
511
512 32
        if ($delimiter === $escapeCharacter) {
513 1
            throw new InvalidArgumentException('Delimiter and escape character must be different.');
514
        }
515
516 31
        if ($path === '') {
517 2
            return [];
518
        }
519
520
        /** @psalm-var non-empty-list<array{0:string, 1:int}> $matches */
521 29
        $matches = preg_split(
522 29
            sprintf(
523 29
                '/(?<!%1$s)((?>%1$s%1$s)*)%2$s/',
524 29
                preg_quote($escapeCharacter, '/'),
525 29
                preg_quote($delimiter, '/')
526 29
            ),
527 29
            $path,
528 29
            -1,
529 29
            PREG_SPLIT_OFFSET_CAPTURE
530 29
        );
531 29
        $result = [];
532 29
        $countResults = count($matches);
533 29
        for ($i = 1; $i < $countResults; $i++) {
534 25
            $l = $matches[$i][1] - $matches[$i - 1][1] - strlen($matches[$i - 1][0]) - 1;
535 25
            $result[] = $matches[$i - 1][0] . ($l > 0 ? str_repeat($escapeCharacter, $l) : '');
536
        }
537 29
        $result[] = $matches[$countResults - 1][0];
538
539 29
        if ($preserveDelimiterEscaping === true) {
540 1
            return $result;
541
        }
542
543 28
        return array_map(
544 28
            static fn (string $key): string => str_replace(
545 28
                [
546 28
                    $escapeCharacter . $escapeCharacter,
547 28
                    $escapeCharacter . $delimiter,
548 28
                ],
549 28
                [
550 28
                    $escapeCharacter,
551 28
                    $delimiter,
552 28
                ],
553 28
                $key
554 28
            ),
555 28
            $result
556 28
        );
557
    }
558
559
    /**
560
     * Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning and end of a string.
561
     * Input string and pattern are treated as UTF-8.
562
     *
563
     * @see https://en.wikipedia.org/wiki/Whitespace_character#Unicode
564
     * @see https://www.php.net/manual/function.preg-replace
565
     *
566
     * @param string|string[] $string The string or an array with strings.
567
     * @param string $pattern PCRE regex pattern to search for, as UTF-8 string. Use {@see preg_quote()} to quote `$pattern` if it contains
568
     * special regular expression characters.
569
     *
570
     * @psalm-template TKey of array-key
571
     * @psalm-param string|array<TKey, string> $string
572
     * @psalm-param non-empty-string $pattern
573
     * @psalm-return ($string is array ? array<TKey, string> : string)
574
     *
575
     * @return string|string[]
576
     */
577 16
    public static function trim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
578
    {
579 16
        self::ensureUtf8Pattern($pattern);
580
581 15
        return preg_replace("#^[$pattern]+|[$pattern]+$#uD", '', $string);
582
    }
583
584
    /**
585
     * Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning of a string.
586
     *
587
     * @see self::trim()
588
     *
589
     * @param string|string[] $string The string or an array with strings.
590
     * @param string $pattern PCRE regex pattern to search for, as UTF-8 string. Use {@see preg_quote()} to quote `$pattern` if it contains
591
     * special regular expression characters.
592
     *
593
     * @psalm-template TKey of array-key
594
     * @psalm-param string|array<TKey, string> $string
595
     * @psalm-param non-empty-string $pattern
596
     * @psalm-return ($string is array ? array<TKey, string> : string)
597
     *
598
     * @return string|string[]
599
     */
600 12
    public static function ltrim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
601
    {
602 12
        self::ensureUtf8Pattern($pattern);
603
604 12
        return preg_replace("#^[$pattern]+#u", '', $string);
605
    }
606
607
    /**
608
     * Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the end of a string.
609
     *
610
     * @see self::trim()
611
     *
612
     * @param string|string[] $string The string or an array with strings.
613
     * @param string $pattern PCRE regex pattern to search for, as UTF-8 string. Use {@see preg_quote()} to quote `$pattern` if it contains
614
     * special regular expression characters.
615
     *
616
     * @psalm-template TKey of array-key
617
     * @psalm-param string|array<TKey, string> $string
618
     * @psalm-param non-empty-string $pattern
619
     * @psalm-return ($string is array ? array<TKey, string> : string)
620
     *
621
     * @return string|string[]
622
     */
623 14
    public static function rtrim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
624
    {
625 14
        self::ensureUtf8Pattern($pattern);
626
627 14
        return preg_replace("#[$pattern]+$#uD", '', $string);
628
    }
629
630
    /**
631
     * Ensure the input string is a valid UTF-8 string.
632
     *
633
     * @param string $pattern The input string.
634
     *
635
     * @throws InvalidArgumentException
636
     */
637 42
    private static function ensureUtf8Pattern(string $pattern): void
638
    {
639 42
        if (!preg_match('##u', $pattern)) {
640 1
            throw new InvalidArgumentException('Pattern is not a valid UTF-8 string.');
641
        }
642
    }
643
}
644