Debian Codegraph @

vendor/symfony/string/AbstractUnicodeString.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\String;
13
14 use Symfony\Component\String\Exception\ExceptionInterface;
15 use Symfony\Component\String\Exception\InvalidArgumentException;
16 use Symfony\Component\String\Exception\RuntimeException;
17
18 /**
19 * Represents a string of abstract Unicode characters.
20 *
21 * Unicode defines 3 types of "characters" (bytes, code points and grapheme clusters).
22 * This class is the abstract type to use as a type-hint when the logic you want to
23 * implement is Unicode-aware but doesn't care about code points vs grapheme clusters.
24 *
25 * @author Nicolas Grekas <[email protected]>
26 *
27 * @throws ExceptionInterface
28 */
29 abstract class AbstractUnicodeString extends AbstractString
30 {
31 public const NFC = \Normalizer::NFC;
32 public const NFD = \Normalizer::NFD;
33 public const NFKC = \Normalizer::NFKC;
34 public const NFKD = \Normalizer::NFKD;
35
36 // all ASCII letters sorted by typical frequency of occurrence
37 private const ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
38
39 // the subset of folded case mappings that is not in lower case mappings
40 private const FOLD_FROM = ['İ', 'µ', 'ſ', "\xCD\x85", 'ς', 'ϐ', 'ϑ', 'ϕ', 'ϖ', 'ϰ', 'ϱ', 'ϵ', 'ẛ', "\xE1\xBE\xBE", 'ß', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'և', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'ẚ', 'ẞ', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'ᾐ', 'ᾑ', 'ᾒ', 'ᾓ', 'ᾔ', 'ᾕ', 'ᾖ', 'ᾗ', 'ᾘ', 'ᾙ', 'ᾚ', 'ᾛ', 'ᾜ', 'ᾝ', 'ᾞ', 'ᾟ', 'ᾠ', 'ᾡ', 'ᾢ', 'ᾣ', 'ᾤ', 'ᾥ', 'ᾦ', 'ᾧ', 'ᾨ', 'ᾩ', 'ᾪ', 'ᾫ', 'ᾬ', 'ᾭ', 'ᾮ', 'ᾯ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'ᾼ', 'ῂ', 'ῃ', 'ῄ', 'ῆ', 'ῇ', 'ῌ', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ῲ', 'ῳ', 'ῴ', 'ῶ', 'ῷ', 'ῼ', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'ſt', 'st', 'ﬓ', 'ﬔ', 'ﬕ', 'ﬖ', 'ﬗ'];
41 private const FOLD_TO = ['i̇', 'μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', 'ṡ', 'ι', 'ss', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'եւ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'aʾ', 'ss', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', 'ἅι', 'ἆι', 'ἇι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὰι', 'αι', 'άι', 'ᾶ', 'ᾶι', 'αι', 'ὴι', 'ηι', 'ήι', 'ῆ', 'ῆι', 'ηι', 'ῒ', 'ῖ', 'ῗ', 'ῢ', 'ῤ', 'ῦ', 'ῧ', 'ὼι', 'ωι', 'ώι', 'ῶ', 'ῶι', 'ωι', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'st', 'st', 'մն', 'մե', 'մի', 'վն', 'մխ'];
42
43 // the subset of https://github.com/unicode-org/cldr/blob/master/common/transforms/Latin-ASCII.xml that is not in NFKD
44 private const TRANSLIT_FROM = ['Æ', 'Ð', 'Ø', 'Þ', 'ß', 'æ', 'ð', 'ø', 'þ', 'Đ', 'đ', 'Ħ', 'ħ', 'ı', 'ĸ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'ʼn', 'Ŋ', 'ŋ', 'Œ', 'œ', 'Ŧ', 'ŧ', 'ƀ', 'Ɓ', 'Ƃ', 'ƃ', 'Ƈ', 'ƈ', 'Ɖ', 'Ɗ', 'Ƌ', 'ƌ', 'Ɛ', 'Ƒ', 'ƒ', 'Ɠ', 'ƕ', 'Ɩ', 'Ɨ', 'Ƙ', 'ƙ', 'ƚ', 'Ɲ', 'ƞ', 'Ƣ', 'ƣ', 'Ƥ', 'ƥ', 'ƫ', 'Ƭ', 'ƭ', 'Ʈ', 'Ʋ', 'Ƴ', 'ƴ', 'Ƶ', 'ƶ', 'DŽ', 'Dž', 'dž', 'Ǥ', 'ǥ', 'ȡ', 'Ȥ', 'ȥ', 'ȴ', 'ȵ', 'ȶ', 'ȷ', 'ȸ', 'ȹ', 'Ⱥ', 'Ȼ', 'ȼ', 'Ƚ', 'Ⱦ', 'ȿ', 'ɀ', 'Ƀ', 'Ʉ', 'Ɇ', 'ɇ', 'Ɉ', 'ɉ', 'Ɍ', 'ɍ', 'Ɏ', 'ɏ', 'ɓ', 'ɕ', 'ɖ', 'ɗ', 'ɛ', 'ɟ', 'ɠ', 'ɡ', 'ɢ', 'ɦ', 'ɧ', 'ɨ', 'ɪ', 'ɫ', 'ɬ', 'ɭ', 'ɱ', 'ɲ', 'ɳ', 'ɴ', 'ɶ', 'ɼ', 'ɽ', 'ɾ', 'ʀ', 'ʂ', 'ʈ', 'ʉ', 'ʋ', 'ʏ', 'ʐ', 'ʑ', 'ʙ', 'ʛ', 'ʜ', 'ʝ', 'ʟ', 'ʠ', 'ʣ', 'ʥ', 'ʦ', 'ʪ', 'ʫ', 'ᴀ', 'ᴁ', 'ᴃ', 'ᴄ', 'ᴅ', 'ᴆ', 'ᴇ', 'ᴊ', 'ᴋ', 'ᴌ', 'ᴍ', 'ᴏ', 'ᴘ', 'ᴛ', 'ᴜ', 'ᴠ', 'ᴡ', 'ᴢ', 'ᵫ', 'ᵬ', 'ᵭ', 'ᵮ', 'ᵯ', 'ᵰ', 'ᵱ', 'ᵲ', 'ᵳ', 'ᵴ', 'ᵵ', 'ᵶ', 'ᵺ', 'ᵻ', 'ᵽ', 'ᵾ', 'ᶀ', 'ᶁ', 'ᶂ', 'ᶃ', 'ᶄ', 'ᶅ', 'ᶆ', 'ᶇ', 'ᶈ', 'ᶉ', 'ᶊ', 'ᶌ', 'ᶍ', 'ᶎ', 'ᶏ', 'ᶑ', 'ᶒ', 'ᶓ', 'ᶖ', 'ᶙ', 'ẚ', 'ẜ', 'ẝ', 'ẞ', 'Ỻ', 'ỻ', 'Ỽ', 'ỽ', 'Ỿ', 'ỿ', '©', '®', '₠', '₢', '₣', '₤', '₧', '₺', '₹', 'ℌ', '℞', '㎧', '㎮', '㏆', '㏗', '㏞', '㏟', '¼', '½', '¾', '⅓', '⅔', '⅕', '⅖', '⅗', '⅘', '⅙', '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '〇', '‘', '’', '‚', '‛', '“', '”', '„', '‟', '′', '″', '〝', '〞', '«', '»', '‹', '›', '‐', '‑', '‒', '–', '—', '―', '︱', '︲', '﹘', '‖', '⁄', '⁅', '⁆', '⁎', '、', '。', '〈', '〉', '《', '》', '〔', '〕', '〘', '〙', '〚', '〛', '︑', '︒', '︹', '︺', '︽', '︾', '︿', '﹀', '﹑', '﹝', '﹞', '⦅', '⦆', '。', '、', '×', '÷', '−', '∕', '∖', '∣', '∥', '≪', '≫', '⦅', '⦆'];
45 private const TRANSLIT_TO = ['AE', 'D', 'O', 'TH', 'ss', 'ae', 'd', 'o', 'th', 'D', 'd', 'H', 'h', 'i', 'q', 'L', 'l', 'L', 'l', '\'n', 'N', 'n', 'OE', 'oe', 'T', 't', 'b', 'B', 'B', 'b', 'C', 'c', 'D', 'D', 'D', 'd', 'E', 'F', 'f', 'G', 'hv', 'I', 'I', 'K', 'k', 'l', 'N', 'n', 'OI', 'oi', 'P', 'p', 't', 'T', 't', 'T', 'V', 'Y', 'y', 'Z', 'z', 'DZ', 'Dz', 'dz', 'G', 'g', 'd', 'Z', 'z', 'l', 'n', 't', 'j', 'db', 'qp', 'A', 'C', 'c', 'L', 'T', 's', 'z', 'B', 'U', 'E', 'e', 'J', 'j', 'R', 'r', 'Y', 'y', 'b', 'c', 'd', 'd', 'e', 'j', 'g', 'g', 'G', 'h', 'h', 'i', 'I', 'l', 'l', 'l', 'm', 'n', 'n', 'N', 'OE', 'r', 'r', 'r', 'R', 's', 't', 'u', 'v', 'Y', 'z', 'z', 'B', 'G', 'H', 'j', 'L', 'q', 'dz', 'dz', 'ts', 'ls', 'lz', 'A', 'AE', 'B', 'C', 'D', 'D', 'E', 'J', 'K', 'L', 'M', 'O', 'P', 'T', 'U', 'V', 'W', 'Z', 'ue', 'b', 'd', 'f', 'm', 'n', 'p', 'r', 'r', 's', 't', 'z', 'th', 'I', 'p', 'U', 'b', 'd', 'f', 'g', 'k', 'l', 'm', 'n', 'p', 'r', 's', 'v', 'x', 'z', 'a', 'd', 'e', 'e', 'i', 'u', 'a', 's', 's', 'SS', 'LL', 'll', 'V', 'v', 'Y', 'y', '(C)', '(R)', 'CE', 'Cr', 'Fr.', 'L.', 'Pts', 'TL', 'Rs', 'x', 'Rx', 'm/s', 'rad/s', 'C/kg', 'pH', 'V/m', 'A/m', ' 1/4', ' 1/2', ' 3/4', ' 1/3', ' 2/3', ' 1/5', ' 2/5', ' 3/5', ' 4/5', ' 1/6', ' 5/6', ' 1/8', ' 3/8', ' 5/8', ' 7/8', ' 1/', '0', '\'', '\'', ',', '\'', '"', '"', ',,', '"', '\'', '"', '"', '"', '<<', '>>', '<', '>', '-', '-', '-', '-', '-', '-', '-', '-', '-', '||', '/', '[', ']', '*', ',', '.', '<', '>', '<<', '>>', '[', ']', '[', ']', '[', ']', ',', '.', '[', ']', '<<', '>>', '<', '>', ',', '[', ']', '((', '))', '.', ',', '*', '/', '-', '/', '\\', '|', '||', '<<', '>>', '((', '))'];
46
47 private static array $transliterators = [];
48 private static array $tableZero;
49 private static array $tableWide;
50
51 public static function fromCodePoints(int ...$codes): static
52 {
53 $string = '';
54
55 foreach ($codes as $code) {
56 if (0x80 > $code %= 0x200000) {
57 $string .= \chr($code);
58 } elseif (0x800 > $code) {
59 $string .= \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F);
60 } elseif (0x10000 > $code) {
61 $string .= \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
62 } else {
63 $string .= \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
64 }
65 }
66
67 return new static($string);
68 }
69
70 /**
71 * Generic UTF-8 to ASCII transliteration.
72 *
73 * Install the intl extension for best results.
74 *
75 * @param string[]|\Transliterator[]|\Closure[] $rules See "*-Latin" rules from Transliterator::listIDs()
76 */
77 public function ascii(array $rules = []): self
78 {
79 $str = clone $this;
80 $s = $str->string;
81 $str->string = '';
82
83 array_unshift($rules, 'nfd');
84 $rules[] = 'latin-ascii';
85
86 if (\function_exists('transliterator_transliterate')) {
87 $rules[] = 'any-latin/bgn';
88 }
89
90 $rules[] = 'nfkd';
91 $rules[] = '[:nonspacing mark:] remove';
92
93 while (\strlen($s) - 1 > $i = strspn($s, self::ASCII)) {
94 if (0 < --$i) {
95 $str->string .= substr($s, 0, $i);
96 $s = substr($s, $i);
97 }
98
99 if (!$rule = array_shift($rules)) {
100 $rules = []; // An empty rule interrupts the next ones
101 }
102
103 if ($rule instanceof \Transliterator) {
104 $s = $rule->transliterate($s);
105 } elseif ($rule instanceof \Closure) {
106 $s = $rule($s);
107 } elseif ($rule) {
108 if ('nfd' === $rule = strtolower($rule)) {
109 normalizer_is_normalized($s, self::NFD) ?: $s = normalizer_normalize($s, self::NFD);
110 } elseif ('nfkd' === $rule) {
111 normalizer_is_normalized($s, self::NFKD) ?: $s = normalizer_normalize($s, self::NFKD);
112 } elseif ('[:nonspacing mark:] remove' === $rule) {
113 $s = preg_replace('/\p{Mn}++/u', '', $s);
114 } elseif ('latin-ascii' === $rule) {
115 $s = str_replace(self::TRANSLIT_FROM, self::TRANSLIT_TO, $s);
116 } elseif ('de-ascii' === $rule) {
117 $s = preg_replace("/([AUO])\u{0308}(?=\p{Ll})/u", '$1e', $s);
118 $s = str_replace(["a\u{0308}", "o\u{0308}", "u\u{0308}", "A\u{0308}", "O\u{0308}", "U\u{0308}"], ['ae', 'oe', 'ue', 'AE', 'OE', 'UE'], $s);
119 } elseif (\function_exists('transliterator_transliterate')) {
120 if (null === $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule)) {
121 if ('any-latin/bgn' === $rule) {
122 $rule = 'any-latin';
123 $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule);
124 }
125
126 if (null === $transliterator) {
127 throw new InvalidArgumentException(\sprintf('Unknown transliteration rule "%s".', $rule));
128 }
129
130 self::$transliterators['any-latin/bgn'] = $transliterator;
131 }
132
133 $s = $transliterator->transliterate($s);
134 }
135 } elseif (!\function_exists('iconv')) {
136 $s = preg_replace('/[^\x00-\x7F]/u', '?', $s);
137 } else {
138 $previousLocale = setlocale(\LC_CTYPE, 0);
139 try {
140 setlocale(\LC_CTYPE, 'C');
141 $s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) {
142 $c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]);
143
144 if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) {
145 throw new \LogicException(\sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class));
146 }
147
148 return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?');
149 }, $s);
150 } finally {
151 setlocale(\LC_CTYPE, $previousLocale);
152 }
153 }
154 }
155
156 $str->string .= $s;
157
158 return $str;
159 }
160
161 public function camel(): static
162 {
163 $str = clone $this;
164 $str->string = str_replace(' ', '', preg_replace_callback('/\b.(?!\p{Lu})/u', static function ($m) {
165 static $i = 0;
166
167 return 1 === ++$i ? ('İ' === $m[0] ? 'i̇' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8');
168 }, preg_replace('/[^\pL0-9]++/u', ' ', $this->string)));
169
170 return $str;
171 }
172
173 /**
174 * @return int[]
175 */
176 public function codePointsAt(int $offset): array
177 {
178 $str = $this->slice($offset, 1);
179
180 if ('' === $str->string) {
181 return [];
182 }
183
184 $codePoints = [];
185
186 foreach (preg_split('//u', $str->string, -1, \PREG_SPLIT_NO_EMPTY) as $c) {
187 $codePoints[] = mb_ord($c, 'UTF-8');
188 }
189
190 return $codePoints;
191 }
192
193 public function folded(bool $compat = true): static
194 {
195 $str = clone $this;
196
197 if (!$compat || !\defined('Normalizer::NFKC_CF')) {
198 $str->string = normalizer_normalize($str->string, $compat ? \Normalizer::NFKC : \Normalizer::NFC);
199 $str->string = mb_strtolower(str_replace(self::FOLD_FROM, self::FOLD_TO, $str->string), 'UTF-8');
200 } else {
201 $str->string = normalizer_normalize($str->string, \Normalizer::NFKC_CF);
202 }
203
204 return $str;
205 }
206
207 public function join(array $strings, ?string $lastGlue = null): static
208 {
209 $str = clone $this;
210
211 $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : '';
212 $str->string = implode($this->string, $strings).$tail;
213
214 if (!preg_match('//u', $str->string)) {
215 throw new InvalidArgumentException('Invalid UTF-8 string.');
216 }
217
218 return $str;
219 }
220
221 public function lower(): static
222 {
223 $str = clone $this;
224 $str->string = mb_strtolower(str_replace('İ', 'i̇', $str->string), 'UTF-8');
225
226 return $str;
227 }
228
229 /**
230 * @param string $locale In the format language_region (e.g. tr_TR)
231 */
232 public function localeLower(string $locale): static
233 {
234 if (null !== $transliterator = $this->getLocaleTransliterator($locale, 'Lower')) {
235 $str = clone $this;
236 $str->string = $transliterator->transliterate($str->string);
237
238 return $str;
239 }
240
241 return $this->lower();
242 }
243
244 public function match(string $regexp, int $flags = 0, int $offset = 0): array
245 {
246 $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match';
247
248 if ($this->ignoreCase) {
249 $regexp .= 'i';
250 }
251
252 set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
253
254 try {
255 if (false === $match($regexp.'u', $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) {
256 throw new RuntimeException('Matching failed with error: '.preg_last_error_msg());
257 }
258 } finally {
259 restore_error_handler();
260 }
261
262 return $matches;
263 }
264
265 public function normalize(int $form = self::NFC): static
266 {
267 if (!\in_array($form, [self::NFC, self::NFD, self::NFKC, self::NFKD], true)) {
268 throw new InvalidArgumentException('Unsupported normalization form.');
269 }
270
271 $str = clone $this;
272 normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
273
274 return $str;
275 }
276
277 public function padBoth(int $length, string $padStr = ' '): static
278 {
279 if ('' === $padStr || !preg_match('//u', $padStr)) {
280 throw new InvalidArgumentException('Invalid UTF-8 string.');
281 }
282
283 $pad = clone $this;
284 $pad->string = $padStr;
285
286 return $this->pad($length, $pad, \STR_PAD_BOTH);
287 }
288
289 public function padEnd(int $length, string $padStr = ' '): static
290 {
291 if ('' === $padStr || !preg_match('//u', $padStr)) {
292 throw new InvalidArgumentException('Invalid UTF-8 string.');
293 }
294
295 $pad = clone $this;
296 $pad->string = $padStr;
297
298 return $this->pad($length, $pad, \STR_PAD_RIGHT);
299 }
300
301 public function padStart(int $length, string $padStr = ' '): static
302 {
303 if ('' === $padStr || !preg_match('//u', $padStr)) {
304 throw new InvalidArgumentException('Invalid UTF-8 string.');
305 }
306
307 $pad = clone $this;
308 $pad->string = $padStr;
309
310 return $this->pad($length, $pad, \STR_PAD_LEFT);
311 }
312
313 public function replaceMatches(string $fromRegexp, string|callable $to): static
314 {
315 if ($this->ignoreCase) {
316 $fromRegexp .= 'i';
317 }
318
319 if (\is_array($to) || $to instanceof \Closure) {
320 $replace = 'preg_replace_callback';
321 $to = static function (array $m) use ($to): string {
322 $to = $to($m);
323
324 if ('' !== $to && (!\is_string($to) || !preg_match('//u', $to))) {
325 throw new InvalidArgumentException('Replace callback must return a valid UTF-8 string.');
326 }
327
328 return $to;
329 };
330 } elseif ('' !== $to && !preg_match('//u', $to)) {
331 throw new InvalidArgumentException('Invalid UTF-8 string.');
332 } else {
333 $replace = 'preg_replace';
334 }
335
336 set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
337
338 try {
339 if (null === $string = $replace($fromRegexp.'u', $to, $this->string)) {
340 $lastError = preg_last_error();
341
342 foreach (get_defined_constants(true)['pcre'] as $k => $v) {
343 if ($lastError === $v && str_ends_with($k, '_ERROR')) {
344 throw new RuntimeException('Matching failed with '.$k.'.');
345 }
346 }
347
348 throw new RuntimeException('Matching failed with unknown error code.');
349 }
350 } finally {
351 restore_error_handler();
352 }
353
354 $str = clone $this;
355 $str->string = $string;
356
357 return $str;
358 }
359
360 public function reverse(): static
361 {
362 $str = clone $this;
363 $str->string = implode('', array_reverse(grapheme_str_split($str->string)));
364
365 return $str;
366 }
367
368 public function snake(): static
369 {
370 $str = $this->camel();
371 $str->string = mb_strtolower(preg_replace(['/(\p{Lu}+)(\p{Lu}\p{Ll})/u', '/([\p{Ll}0-9])(\p{Lu})/u'], '\1_\2', $str->string), 'UTF-8');
372
373 return $str;
374 }
375
376 public function title(bool $allWords = false): static
377 {
378 $str = clone $this;
379
380 $limit = $allWords ? -1 : 1;
381
382 $str->string = preg_replace_callback('/\b./u', static fn (array $m): string => mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8'), $str->string, $limit);
383
384 return $str;
385 }
386
387 /**
388 * @param string $locale In the format language_region (e.g. tr_TR)
389 */
390 public function localeTitle(string $locale): static
391 {
392 if (null !== $transliterator = $this->getLocaleTransliterator($locale, 'Title')) {
393 $str = clone $this;
394 $str->string = $transliterator->transliterate($str->string);
395
396 return $str;
397 }
398
399 return $this->title();
400 }
401
402 public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
403 {
404 if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
405 throw new InvalidArgumentException('Invalid UTF-8 chars.');
406 }
407 $chars = preg_quote($chars);
408
409 $str = clone $this;
410 $str->string = preg_replace("{^[$chars]++|[$chars]++$}uD", '', $str->string);
411
412 return $str;
413 }
414
415 public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
416 {
417 if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
418 throw new InvalidArgumentException('Invalid UTF-8 chars.');
419 }
420 $chars = preg_quote($chars);
421
422 $str = clone $this;
423 $str->string = preg_replace("{[$chars]++$}uD", '', $str->string);
424
425 return $str;
426 }
427
428 public function trimPrefix($prefix): static
429 {
430 if (!$this->ignoreCase) {
431 return parent::trimPrefix($prefix);
432 }
433
434 $str = clone $this;
435
436 if ($prefix instanceof \Traversable) {
437 $prefix = iterator_to_array($prefix, false);
438 } elseif ($prefix instanceof parent) {
439 $prefix = $prefix->string;
440 }
441
442 $prefix = implode('|', array_map('preg_quote', (array) $prefix));
443 $str->string = preg_replace("{^(?:$prefix)}iuD", '', $this->string);
444
445 return $str;
446 }
447
448 public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
449 {
450 if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
451 throw new InvalidArgumentException('Invalid UTF-8 chars.');
452 }
453 $chars = preg_quote($chars);
454
455 $str = clone $this;
456 $str->string = preg_replace("{^[$chars]++}uD", '', $str->string);
457
458 return $str;
459 }
460
461 public function trimSuffix($suffix): static
462 {
463 if (!$this->ignoreCase) {
464 return parent::trimSuffix($suffix);
465 }
466
467 $str = clone $this;
468
469 if ($suffix instanceof \Traversable) {
470 $suffix = iterator_to_array($suffix, false);
471 } elseif ($suffix instanceof parent) {
472 $suffix = $suffix->string;
473 }
474
475 $suffix = implode('|', array_map('preg_quote', (array) $suffix));
476 $str->string = preg_replace("{(?:$suffix)$}iuD", '', $this->string);
477
478 return $str;
479 }
480
481 public function upper(): static
482 {
483 $str = clone $this;
484 $str->string = mb_strtoupper($str->string, 'UTF-8');
485
486 return $str;
487 }
488
489 /**
490 * @param string $locale In the format language_region (e.g. tr_TR)
491 */
492 public function localeUpper(string $locale): static
493 {
494 if (null !== $transliterator = $this->getLocaleTransliterator($locale, 'Upper')) {
495 $str = clone $this;
496 $str->string = $transliterator->transliterate($str->string);
497
498 return $str;
499 }
500
501 return $this->upper();
502 }
503
504 public function width(bool $ignoreAnsiDecoration = true): int
505 {
506 $width = 0;
507 $s = str_replace(["\x00", "\x05", "\x07"], '', $this->string);
508
509 if (str_contains($s, "\r")) {
510 $s = str_replace(["\r\n", "\r"], "\n", $s);
511 }
512
513 if (!$ignoreAnsiDecoration) {
514 $s = preg_replace('/[\p{Cc}\x7F]++/u', '', $s);
515 }
516
517 foreach (explode("\n", $s) as $s) {
518 if ($ignoreAnsiDecoration) {
519 $s = preg_replace('/(?:\x1B(?:
520 \[ [\x30-\x3F]*+ [\x20-\x2F]*+ [\x40-\x7E]
521 | [P\]X^_] .*? \x1B\\\\
522 | [\x41-\x7E]
523 )|[\p{Cc}\x7F]++)/xu', '', $s);
524 }
525
526 $lineWidth = $this->wcswidth($s);
527
528 if ($lineWidth > $width) {
529 $width = $lineWidth;
530 }
531 }
532
533 return $width;
534 }
535
536 private function pad(int $len, self $pad, int $type): static
537 {
538 $sLen = $this->length();
539
540 if ($len <= $sLen) {
541 return clone $this;
542 }
543
544 $padLen = $pad->length();
545 $freeLen = $len - $sLen;
546 $len = $freeLen % $padLen;
547
548 switch ($type) {
549 case \STR_PAD_RIGHT:
550 return $this->append(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
551
552 case \STR_PAD_LEFT:
553 return $this->prepend(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
554
555 case \STR_PAD_BOTH:
556 $freeLen /= 2;
557
558 $rightLen = ceil($freeLen);
559 $len = $rightLen % $padLen;
560 $str = $this->append(str_repeat($pad->string, intdiv($rightLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
561
562 $leftLen = floor($freeLen);
563 $len = $leftLen % $padLen;
564
565 return $str->prepend(str_repeat($pad->string, intdiv($leftLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
566
567 default:
568 throw new InvalidArgumentException('Invalid padding type.');
569 }
570 }
571
572 /**
573 * Based on https://github.com/jquast/wcwidth, a Python implementation of https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c.
574 */
575 private function wcswidth(string $string): int
576 {
577 $width = 0;
578 $lastChar = null;
579 $lastWidth = null;
580
581 foreach (preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) {
582 $codePoint = mb_ord($c, 'UTF-8');
583
584 if (0 === $codePoint // NULL
585 || 0x034F === $codePoint // COMBINING GRAPHEME JOINER
586 || (0x200B <= $codePoint && 0x200F >= $codePoint) // ZERO WIDTH SPACE to RIGHT-TO-LEFT MARK
587 || 0x2028 === $codePoint // LINE SEPARATOR
588 || 0x2029 === $codePoint // PARAGRAPH SEPARATOR
589 || (0x202A <= $codePoint && 0x202E >= $codePoint) // LEFT-TO-RIGHT EMBEDDING to RIGHT-TO-LEFT OVERRIDE
590 || (0x2060 <= $codePoint && 0x2063 >= $codePoint) // WORD JOINER to INVISIBLE SEPARATOR
591 ) {
592 continue;
593 }
594
595 // Non printable characters
596 if (32 > $codePoint // C0 control characters
597 || (0x07F <= $codePoint && 0x0A0 > $codePoint) // C1 control characters and DEL
598 ) {
599 return -1;
600 }
601
602 if (0xFE0F === $codePoint) {
603 if (\PCRE_VERSION_MAJOR < 10 || \PCRE_VERSION_MAJOR === 10 && \PCRE_VERSION_MINOR < 40) {
604 $regex = '/\p{So}/u';
605 } else {
606 $regex = '/\p{Emoji}/u';
607 }
608 if (null !== $lastChar && 1 === $lastWidth && preg_match($regex, $lastChar)) {
609 ++$width;
610 $lastWidth = 2;
611 }
612
613 continue;
614 }
615
616 self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php';
617
618 if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) {
619 $lbound = 0;
620 while ($ubound >= $lbound) {
621 $mid = floor(($lbound + $ubound) / 2);
622
623 if ($codePoint > self::$tableZero[$mid][1]) {
624 $lbound = $mid + 1;
625 } elseif ($codePoint < self::$tableZero[$mid][0]) {
626 $ubound = $mid - 1;
627 } else {
628 continue 2;
629 }
630 }
631 }
632
633 self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php';
634
635 if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) {
636 $lbound = 0;
637 while ($ubound >= $lbound) {
638 $mid = floor(($lbound + $ubound) / 2);
639
640 if ($codePoint > self::$tableWide[$mid][1]) {
641 $lbound = $mid + 1;
642 } elseif ($codePoint < self::$tableWide[$mid][0]) {
643 $ubound = $mid - 1;
644 } else {
645 $width += 2;
646 $lastChar = $c;
647 $lastWidth = 2;
648
649 continue 2;
650 }
651 }
652 }
653
654 ++$width;
655 $lastChar = $c;
656 $lastWidth = 1;
657 }
658
659 return $width;
660 }
661
662 private function getLocaleTransliterator(string $locale, string $id): ?\Transliterator
663 {
664 $rule = $locale.'-'.$id;
665 if (\array_key_exists($rule, self::$transliterators)) {
666 return self::$transliterators[$rule];
667 }
668
669 if (null !== $transliterator = self::$transliterators[$rule] = \Transliterator::create($rule)) {
670 return $transliterator;
671 }
672
673 // Try to find a parent locale (nl_BE -> nl)
674 if (false === $i = strpos($locale, '_')) {
675 return null;
676 }
677
678 $parentRule = substr_replace($locale, '-'.$id, $i);
679
680 // Parent locale was already cached, return and store as current locale
681 if (\array_key_exists($parentRule, self::$transliterators)) {
682 return self::$transliterators[$rule] = self::$transliterators[$parentRule];
683 }
684
685 // Create transliterator based on parent locale and cache the result on both initial and parent locale values
686 $transliterator = \Transliterator::create($parentRule);
687
688 return self::$transliterators[$rule] = self::$transliterators[$parentRule] = $transliterator;
689 }
690 }