PluginProbe
SendWP / 1.4.4
SendWP v1.4.4
trunk 0.0.1 0.0.2 0.0.3 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.1 1.2.10 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3 1.3.1 1.4.4 1.4.5 1.4.6 1.4.8
sendwp / vendor / symfony / string / AbstractUnicodeString.php

AbstractUnicodeString.php in SendWP 1.4.4, at vendor/symfony/string/AbstractUnicodeString.php

613 lines 25.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
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 <p@tchwork.com>
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\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 'ῷ', 'ῼ', 'ff', 'fi', 'fl', 'ffi', 'ffl', '�
42 ', '', '', '', '', '', ''];
43 private const FOLD_TO = ['i̇', 'μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', 'ṡ', 'ι', 'ss', 'ʼn', 'ǰ', 'ΐ', 'ΰ', 'եւ', 'ẖ', 'ẗ', 'ẘ', 'ẙ', 'aʾ', 'ss', 'ὐ', 'ὒ', 'ὔ', 'ὖ', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', '�
44 ι', 'ἆι', 'ἇι', 'ἀι', 'ἁι', 'ἂι', 'ἃι', 'ἄι', '�
45 ι', 'ἆι', 'ἇι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ἠι', 'ἡι', 'ἢι', 'ἣι', 'ἤι', 'ἥι', 'ἦι', 'ἧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὠι', 'ὡι', 'ὢι', 'ὣι', 'ὤι', 'ὥι', 'ὦι', 'ὧι', 'ὰι', 'αι', 'άι', '', 'ᾶι', 'αι', 'ὴι', 'ηι', 'ήι', '', 'ῆι', 'ηι', '', '', '', '', '', '', '', 'ὼι', 'ωι', 'ώι', '', 'ῶι', 'ωι', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'st', 'st', 'մն', 'մե', 'մի', 'վն', 'մխ'];
46
47 // the subset of https://github.com/unicode-org/cldr/blob/master/common/transforms/Latin-ASCII.xml that is not in NFKD
48 private const TRANSLIT_FROM = ['Æ', 'Ð', 'Ø', 'Þ', 'ß', 'æ', 'ð', 'ø', 'þ', 'Đ', 'đ', 'Ħ', 'ħ', 'ı', 'ĸ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'ʼn', 'Ŋ', 'ŋ', 'Œ', 'œ', 'Ŧ', 'ŧ', 'ƀ', 'Ɓ', 'Ƃ', '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'ᵽ', 'ᵾ', 'ᶀ', 'ᶁ', 'ᶂ', 'ᶃ', 'ᶄ', '�
51 ', 'ᶆ', 'ᶇ', 'ᶈ', 'ᶉ', 'ᶊ', 'ᶌ', 'ᶍ', 'ᶎ', 'ᶏ', 'ᶑ', 'ᶒ', 'ᶓ', 'ᶖ', 'ᶙ', 'ẚ', 'ẜ', 'ẝ', 'ẞ', 'Ỻ', 'ỻ', 'Ỽ', 'ỽ', 'Ỿ', 'ỿ', '©', '®', '₠', '₢', '₣', '₤', '₧', '₺', '₹', 'ℌ', '℞', '㎧', '㎮', '㏆', '㏗', '㏞', '㏟', '¼', '½', '¾', '�
52 �', '�
53 �', '�
54 �', '�
55 �', '�
56 �', '�
57 �', '�
58 �', '�
59 �', '�
60 �', '�
61 �', '�
62 �', '�
63 �', '�
64 �', '〇', '‘', '’', '‚', '‛', '“', '”', '„', '‟', '′', '″', '〝', '〞', '«', '»', '‹', '›', '‐', '‑', '‒', '–', '—', '―', '︱', '︲', '﹘', '‖', '⁄', '�
65 ', '⁆', '⁎', '、', '。', '〈', '〉', '《', '》', '〔', '〕', '〘', '〙', '〚', '〛', '︑', '︒', '︹', '︺', '︽', '︾', '︿', '﹀', '﹑', '﹝', '﹞', '⦅', '⦆', '。', '、', '×', '÷', '−', '∕', '∖', '∣', '∥', '≪', '≫', '�
66 ', ''];
67 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', '\'', '\'', ',', '\'', '"', '"', ',,', '"', '\'', '"', '"', '"', '<<', '>>', '<', '>', '-', '-', '-', '-', '-', '-', '-', '-', '-', '||', '/', '[', ']', '*', ',', '.', '<', '>', '<<', '>>', '[', ']', '[', ']', '[', ']', ',', '.', '[', ']', '<<', '>>', '<', '>', ',', '[', ']', '((', '))', '.', ',', '*', '/', '-', '/', '\\', '|', '||', '<<', '>>', '((', '))'];
68
69 private static $transliterators = [];
70 private static $tableZero;
71 private static $tableWide;
72
73 public static function fromCodePoints(int ...$codes): static
74 {
75 $string = '';
76
77 foreach ($codes as $code) {
78 if (0x80 > $code %= 0x200000) {
79 $string .= \chr($code);
80 } elseif (0x800 > $code) {
81 $string .= \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F);
82 } elseif (0x10000 > $code) {
83 $string .= \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
84 } else {
85 $string .= \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F);
86 }
87 }
88
89 return new static($string);
90 }
91
92 /**
93 * Generic UTF-8 to ASCII transliteration.
94 *
95 * Install the intl extension for best results.
96 *
97 * @param string[]|\Transliterator[]|\Closure[] $rules See "*-Latin" rules from Transliterator::listIDs()
98 */
99 public function ascii(array $rules = []): self
100 {
101 $str = clone $this;
102 $s = $str->string;
103 $str->string = '';
104
105 array_unshift($rules, 'nfd');
106 $rules[] = 'latin-ascii';
107
108 if (\function_exists('transliterator_transliterate')) {
109 $rules[] = 'any-latin/bgn';
110 }
111
112 $rules[] = 'nfkd';
113 $rules[] = '[:nonspacing mark:] remove';
114
115 while (\strlen($s) - 1 > $i = strspn($s, self::ASCII)) {
116 if (0 < --$i) {
117 $str->string .= substr($s, 0, $i);
118 $s = substr($s, $i);
119 }
120
121 if (!$rule = array_shift($rules)) {
122 $rules = []; // An empty rule interrupts the next ones
123 }
124
125 if ($rule instanceof \Transliterator) {
126 $s = $rule->transliterate($s);
127 } elseif ($rule instanceof \Closure) {
128 $s = $rule($s);
129 } elseif ($rule) {
130 if ('nfd' === $rule = strtolower($rule)) {
131 normalizer_is_normalized($s, self::NFD) ?: $s = normalizer_normalize($s, self::NFD);
132 } elseif ('nfkd' === $rule) {
133 normalizer_is_normalized($s, self::NFKD) ?: $s = normalizer_normalize($s, self::NFKD);
134 } elseif ('[:nonspacing mark:] remove' === $rule) {
135 $s = preg_replace('/\p{Mn}++/u', '', $s);
136 } elseif ('latin-ascii' === $rule) {
137 $s = str_replace(self::TRANSLIT_FROM, self::TRANSLIT_TO, $s);
138 } elseif ('de-ascii' === $rule) {
139 $s = preg_replace("/([AUO])\u{0308}(?=\p{Ll})/u", '$1e', $s);
140 $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);
141 } elseif (\function_exists('transliterator_transliterate')) {
142 if (null === $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule)) {
143 if ('any-latin/bgn' === $rule) {
144 $rule = 'any-latin';
145 $transliterator = self::$transliterators[$rule] ??= \Transliterator::create($rule);
146 }
147
148 if (null === $transliterator) {
149 throw new InvalidArgumentException(sprintf('Unknown transliteration rule "%s".', $rule));
150 }
151
152 self::$transliterators['any-latin/bgn'] = $transliterator;
153 }
154
155 $s = $transliterator->transliterate($s);
156 }
157 } elseif (!\function_exists('iconv')) {
158 $s = preg_replace('/[^\x00-\x7F]/u', '?', $s);
159 } else {
160 $s = @preg_replace_callback('/[^\x00-\x7F]/u', static function ($c) {
161 $c = (string) iconv('UTF-8', 'ASCII//TRANSLIT', $c[0]);
162
163 if ('' === $c && '' === iconv('UTF-8', 'ASCII//TRANSLIT', '²')) {
164 throw new \LogicException(sprintf('"%s" requires a translit-able iconv implementation, try installing "gnu-libiconv" if you\'re using Alpine Linux.', static::class));
165 }
166
167 return 1 < \strlen($c) ? ltrim($c, '\'`"^~') : ('' !== $c ? $c : '?');
168 }, $s);
169 }
170 }
171
172 $str->string .= $s;
173
174 return $str;
175 }
176
177 public function camel(): static
178 {
179 $str = clone $this;
180 $str->string = str_replace(' ', '', preg_replace_callback('/\b.(?![A-Z]{2,})/u', static function ($m) {
181 static $i = 0;
182
183 return 1 === ++$i ? ('İ' === $m[0] ? '' : mb_strtolower($m[0], 'UTF-8')) : mb_convert_case($m[0], \MB_CASE_TITLE, 'UTF-8');
184 }, preg_replace('/[^\pL0-9]++/u', ' ', $this->string)));
185
186 return $str;
187 }
188
189 /**
190 * @return int[]
191 */
192 public function codePointsAt(int $offset): array
193 {
194 $str = $this->slice($offset, 1);
195
196 if ('' === $str->string) {
197 return [];
198 }
199
200 $codePoints = [];
201
202 foreach (preg_split('//u', $str->string, -1, \PREG_SPLIT_NO_EMPTY) as $c) {
203 $codePoints[] = mb_ord($c, 'UTF-8');
204 }
205
206 return $codePoints;
207 }
208
209 public function folded(bool $compat = true): static
210 {
211 $str = clone $this;
212
213 if (!$compat || !\defined('Normalizer::NFKC_CF')) {
214 $str->string = normalizer_normalize($str->string, $compat ? \Normalizer::NFKC : \Normalizer::NFC);
215 $str->string = mb_strtolower(str_replace(self::FOLD_FROM, self::FOLD_TO, $this->string), 'UTF-8');
216 } else {
217 $str->string = normalizer_normalize($str->string, \Normalizer::NFKC_CF);
218 }
219
220 return $str;
221 }
222
223 public function join(array $strings, string $lastGlue = null): static
224 {
225 $str = clone $this;
226
227 $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : '';
228 $str->string = implode($this->string, $strings).$tail;
229
230 if (!preg_match('//u', $str->string)) {
231 throw new InvalidArgumentException('Invalid UTF-8 string.');
232 }
233
234 return $str;
235 }
236
237 public function lower(): static
238 {
239 $str = clone $this;
240 $str->string = mb_strtolower(str_replace('İ', '', $str->string), 'UTF-8');
241
242 return $str;
243 }
244
245 public function match(string $regexp, int $flags = 0, int $offset = 0): array
246 {
247 $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match';
248
249 if ($this->ignoreCase) {
250 $regexp .= 'i';
251 }
252
253 set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
254
255 try {
256 if (false === $match($regexp.'u', $this->string, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset)) {
257 throw new RuntimeException('Matching failed with error: '.preg_last_error_msg());
258 }
259 } finally {
260 restore_error_handler();
261 }
262
263 return $matches;
264 }
265
266 public function normalize(int $form = self::NFC): static
267 {
268 if (!\in_array($form, [self::NFC, self::NFD, self::NFKC, self::NFKD])) {
269 throw new InvalidArgumentException('Unsupported normalization form.');
270 }
271
272 $str = clone $this;
273 normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
274
275 return $str;
276 }
277
278 public function padBoth(int $length, string $padStr = ' '): static
279 {
280 if ('' === $padStr || !preg_match('//u', $padStr)) {
281 throw new InvalidArgumentException('Invalid UTF-8 string.');
282 }
283
284 $pad = clone $this;
285 $pad->string = $padStr;
286
287 return $this->pad($length, $pad, \STR_PAD_BOTH);
288 }
289
290 public function padEnd(int $length, string $padStr = ' '): static
291 {
292 if ('' === $padStr || !preg_match('//u', $padStr)) {
293 throw new InvalidArgumentException('Invalid UTF-8 string.');
294 }
295
296 $pad = clone $this;
297 $pad->string = $padStr;
298
299 return $this->pad($length, $pad, \STR_PAD_RIGHT);
300 }
301
302 public function padStart(int $length, string $padStr = ' '): static
303 {
304 if ('' === $padStr || !preg_match('//u', $padStr)) {
305 throw new InvalidArgumentException('Invalid UTF-8 string.');
306 }
307
308 $pad = clone $this;
309 $pad->string = $padStr;
310
311 return $this->pad($length, $pad, \STR_PAD_LEFT);
312 }
313
314 public function replaceMatches(string $fromRegexp, string|callable $to): static
315 {
316 if ($this->ignoreCase) {
317 $fromRegexp .= 'i';
318 }
319
320 if (\is_array($to) || $to instanceof \Closure) {
321 $replace = 'preg_replace_callback';
322 $to = static function (array $m) use ($to): string {
323 $to = $to($m);
324
325 if ('' !== $to && (!\is_string($to) || !preg_match('//u', $to))) {
326 throw new InvalidArgumentException('Replace callback must return a valid UTF-8 string.');
327 }
328
329 return $to;
330 };
331 } elseif ('' !== $to && !preg_match('//u', $to)) {
332 throw new InvalidArgumentException('Invalid UTF-8 string.');
333 } else {
334 $replace = 'preg_replace';
335 }
336
337 set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
338
339 try {
340 if (null === $string = $replace($fromRegexp.'u', $to, $this->string)) {
341 $lastError = preg_last_error();
342
343 foreach (get_defined_constants(true)['pcre'] as $k => $v) {
344 if ($lastError === $v && str_ends_with($k, '_ERROR')) {
345 throw new RuntimeException('Matching failed with '.$k.'.');
346 }
347 }
348
349 throw new RuntimeException('Matching failed with unknown error code.');
350 }
351 } finally {
352 restore_error_handler();
353 }
354
355 $str = clone $this;
356 $str->string = $string;
357
358 return $str;
359 }
360
361 public function reverse(): static
362 {
363 $str = clone $this;
364 $str->string = implode('', array_reverse(preg_split('/(\X)/u', $str->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY)));
365
366 return $str;
367 }
368
369 public function snake(): static
370 {
371 $str = $this->camel();
372 $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');
373
374 return $str;
375 }
376
377 public function title(bool $allWords = false): static
378 {
379 $str = clone $this;
380
381 $limit = $allWords ? -1 : 1;
382
383 $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);
384
385 return $str;
386 }
387
388 public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
389 {
390 if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
391 throw new InvalidArgumentException('Invalid UTF-8 chars.');
392 }
393 $chars = preg_quote($chars);
394
395 $str = clone $this;
396 $str->string = preg_replace("{^[$chars]++|[$chars]++$}uD", '', $str->string);
397
398 return $str;
399 }
400
401 public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
402 {
403 if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
404 throw new InvalidArgumentException('Invalid UTF-8 chars.');
405 }
406 $chars = preg_quote($chars);
407
408 $str = clone $this;
409 $str->string = preg_replace("{[$chars]++$}uD", '', $str->string);
410
411 return $str;
412 }
413
414 public function trimPrefix($prefix): static
415 {
416 if (!$this->ignoreCase) {
417 return parent::trimPrefix($prefix);
418 }
419
420 $str = clone $this;
421
422 if ($prefix instanceof \Traversable) {
423 $prefix = iterator_to_array($prefix, false);
424 } elseif ($prefix instanceof parent) {
425 $prefix = $prefix->string;
426 }
427
428 $prefix = implode('|', array_map('preg_quote', (array) $prefix));
429 $str->string = preg_replace("{^(?:$prefix)}iuD", '', $this->string);
430
431 return $str;
432 }
433
434 public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static
435 {
436 if (" \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}" !== $chars && !preg_match('//u', $chars)) {
437 throw new InvalidArgumentException('Invalid UTF-8 chars.');
438 }
439 $chars = preg_quote($chars);
440
441 $str = clone $this;
442 $str->string = preg_replace("{^[$chars]++}uD", '', $str->string);
443
444 return $str;
445 }
446
447 public function trimSuffix($suffix): static
448 {
449 if (!$this->ignoreCase) {
450 return parent::trimSuffix($suffix);
451 }
452
453 $str = clone $this;
454
455 if ($suffix instanceof \Traversable) {
456 $suffix = iterator_to_array($suffix, false);
457 } elseif ($suffix instanceof parent) {
458 $suffix = $suffix->string;
459 }
460
461 $suffix = implode('|', array_map('preg_quote', (array) $suffix));
462 $str->string = preg_replace("{(?:$suffix)$}iuD", '', $this->string);
463
464 return $str;
465 }
466
467 public function upper(): static
468 {
469 $str = clone $this;
470 $str->string = mb_strtoupper($str->string, 'UTF-8');
471
472 return $str;
473 }
474
475 public function width(bool $ignoreAnsiDecoration = true): int
476 {
477 $width = 0;
478 $s = str_replace(["\x00", "\x05", "\x07"], '', $this->string);
479
480 if (str_contains($s, "\r")) {
481 $s = str_replace(["\r\n", "\r"], "\n", $s);
482 }
483
484 if (!$ignoreAnsiDecoration) {
485 $s = preg_replace('/[\p{Cc}\x7F]++/u', '', $s);
486 }
487
488 foreach (explode("\n", $s) as $s) {
489 if ($ignoreAnsiDecoration) {
490 $s = preg_replace('/(?:\x1B(?:
491 \[ [\x30-\x3F]*+ [\x20-\x2F]*+ [\x40-\x7E]
492 | [P\]X^_] .*? \x1B\\\\
493 | [\x41-\x7E]
494 )|[\p{Cc}\x7F]++)/xu', '', $s);
495 }
496
497 $lineWidth = $this->wcswidth($s);
498
499 if ($lineWidth > $width) {
500 $width = $lineWidth;
501 }
502 }
503
504 return $width;
505 }
506
507 private function pad(int $len, self $pad, int $type): static
508 {
509 $sLen = $this->length();
510
511 if ($len <= $sLen) {
512 return clone $this;
513 }
514
515 $padLen = $pad->length();
516 $freeLen = $len - $sLen;
517 $len = $freeLen % $padLen;
518
519 switch ($type) {
520 case \STR_PAD_RIGHT:
521 return $this->append(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
522
523 case \STR_PAD_LEFT:
524 return $this->prepend(str_repeat($pad->string, intdiv($freeLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
525
526 case \STR_PAD_BOTH:
527 $freeLen /= 2;
528
529 $rightLen = ceil($freeLen);
530 $len = $rightLen % $padLen;
531 $str = $this->append(str_repeat($pad->string, intdiv($rightLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
532
533 $leftLen = floor($freeLen);
534 $len = $leftLen % $padLen;
535
536 return $str->prepend(str_repeat($pad->string, intdiv($leftLen, $padLen)).($len ? $pad->slice(0, $len) : ''));
537
538 default:
539 throw new InvalidArgumentException('Invalid padding type.');
540 }
541 }
542
543 /**
544 * Based on https://github.com/jquast/wcwidth, a Python implementation of https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c.
545 */
546 private function wcswidth(string $string): int
547 {
548 $width = 0;
549
550 foreach (preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) {
551 $codePoint = mb_ord($c, 'UTF-8');
552
553 if (0 === $codePoint // NULL
554 || 0x034F === $codePoint // COMBINING GRAPHEME JOINER
555 || (0x200B <= $codePoint && 0x200F >= $codePoint) // ZERO WIDTH SPACE to RIGHT-TO-LEFT MARK
556 || 0x2028 === $codePoint // LINE SEPARATOR
557 || 0x2029 === $codePoint // PARAGRAPH SEPARATOR
558 || (0x202A <= $codePoint && 0x202E >= $codePoint) // LEFT-TO-RIGHT EMBEDDING to RIGHT-TO-LEFT OVERRIDE
559 || (0x2060 <= $codePoint && 0x2063 >= $codePoint) // WORD JOINER to INVISIBLE SEPARATOR
560 ) {
561 continue;
562 }
563
564 // Non printable characters
565 if (32 > $codePoint // C0 control characters
566 || (0x07F <= $codePoint && 0x0A0 > $codePoint) // C1 control characters and DEL
567 ) {
568 return -1;
569 }
570
571 self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php';
572
573 if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) {
574 $lbound = 0;
575 while ($ubound >= $lbound) {
576 $mid = floor(($lbound + $ubound) / 2);
577
578 if ($codePoint > self::$tableZero[$mid][1]) {
579 $lbound = $mid + 1;
580 } elseif ($codePoint < self::$tableZero[$mid][0]) {
581 $ubound = $mid - 1;
582 } else {
583 continue 2;
584 }
585 }
586 }
587
588 self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php';
589
590 if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) {
591 $lbound = 0;
592 while ($ubound >= $lbound) {
593 $mid = floor(($lbound + $ubound) / 2);
594
595 if ($codePoint > self::$tableWide[$mid][1]) {
596 $lbound = $mid + 1;
597 } elseif ($codePoint < self::$tableWide[$mid][0]) {
598 $ubound = $mid - 1;
599 } else {
600 $width += 2;
601
602 continue 2;
603 }
604 }
605 }
606
607 ++$width;
608 }
609
610 return $width;
611 }
612 }
613