Debian Codegraph @

vendor/symfony/string/UnicodeString.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
17 /**
18 * Represents a string of Unicode grapheme clusters encoded as UTF-8.
19 *
20 * A letter followed by combining characters (accents typically) form what Unicode defines
21 * as a grapheme cluster: a character as humans mean it in written texts. This class knows
22 * about the concept and won't split a letter apart from its combining accents. It also
23 * ensures all string comparisons happen on their canonically-composed representation,
24 * ignoring e.g. the order in which accents are listed when a letter has many of them.
25 *
26 * @see https://unicode.org/reports/tr15/
27 *
28 * @author Nicolas Grekas <[email protected]>
29 * @author Hugo Hamon <[email protected]>
30 *
31 * @throws ExceptionInterface
32 */
33 class UnicodeString extends AbstractUnicodeString
34 {
35 public function __construct(string $string = '')
36 {
37 if ('' === $string || normalizer_is_normalized($this->string = $string)) {
38 return;
39 }
40
41 if (false === $string = normalizer_normalize($string)) {
42 throw new InvalidArgumentException('Invalid UTF-8 string.');
43 }
44
45 $this->string = $string;
46 }
47
48 public function append(string ...$suffix): static
49 {
50 $str = clone $this;
51 $str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix));
52
53 if (normalizer_is_normalized($str->string)) {
54 return $str;
55 }
56
57 if (false === $string = normalizer_normalize($str->string)) {
58 throw new InvalidArgumentException('Invalid UTF-8 string.');
59 }
60
61 $str->string = $string;
62
63 return $str;
64 }
65
66 public function chunk(int $length = 1): array
67 {
68 if (1 > $length) {
69 throw new InvalidArgumentException('The chunk length must be greater than zero.');
70 }
71
72 if ('' === $this->string) {
73 return [];
74 }
75
76 $rx = '/(';
77 while (65535 < $length) {
78 $rx .= '\X{65535}';
79 $length -= 65535;
80 }
81 $rx .= '\X{'.$length.'})/u';
82
83 $str = clone $this;
84 $chunks = [];
85
86 foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) {
87 $str->string = $chunk;
88 $chunks[] = clone $str;
89 }
90
91 return $chunks;
92 }
93
94 public function endsWith(string|iterable|AbstractString $suffix): bool
95 {
96 if ($suffix instanceof AbstractString) {
97 $suffix = $suffix->string;
98 } elseif (!\is_string($suffix)) {
99 return parent::endsWith($suffix);
100 }
101
102 $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
103 normalizer_is_normalized($suffix, $form) ?: $suffix = normalizer_normalize($suffix, $form);
104
105 if ('' === $suffix || false === $suffix) {
106 return false;
107 }
108
109 if (false === $grapheme = grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix))) {
110 $grapheme = '';
111 }
112
113 if ($this->ignoreCase) {
114 return 0 === mb_stripos($grapheme, $suffix, 0, 'UTF-8');
115 }
116
117 return $suffix === $grapheme;
118 }
119
120 public function equalsTo(string|iterable|AbstractString $string): bool
121 {
122 if ($string instanceof AbstractString) {
123 $string = $string->string;
124 } elseif (!\is_string($string)) {
125 return parent::equalsTo($string);
126 }
127
128 $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
129 normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form);
130
131 if ('' !== $string && false !== $string && $this->ignoreCase) {
132 return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8');
133 }
134
135 return $string === $this->string;
136 }
137
138 public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int
139 {
140 if ($needle instanceof AbstractString) {
141 $needle = $needle->string;
142 } elseif (!\is_string($needle)) {
143 return parent::indexOf($needle, $offset);
144 }
145
146 $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
147 normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
148
149 if ('' === $needle || false === $needle) {
150 return null;
151 }
152
153 try {
154 $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset);
155 } catch (\ValueError) {
156 return null;
157 }
158
159 return false === $i ? null : $i;
160 }
161
162 public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int
163 {
164 if ($needle instanceof AbstractString) {
165 $needle = $needle->string;
166 } elseif (!\is_string($needle)) {
167 return parent::indexOfLast($needle, $offset);
168 }
169
170 $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
171 normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
172
173 if ('' === $needle || false === $needle) {
174 return null;
175 }
176
177 $string = $this->string;
178
179 if (0 > $offset) {
180 // workaround https://bugs.php.net/74264
181 if (0 > $offset += grapheme_strlen($needle)) {
182 $string = grapheme_substr($string, 0, $offset);
183 }
184 $offset = 0;
185 }
186
187 $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset);
188
189 return false === $i ? null : $i;
190 }
191
192 public function join(array $strings, ?string $lastGlue = null): static
193 {
194 $str = parent::join($strings, $lastGlue);
195 normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
196
197 return $str;
198 }
199
200 public function length(): int
201 {
202 return grapheme_strlen($this->string);
203 }
204
205 public function normalize(int $form = self::NFC): static
206 {
207 $str = clone $this;
208
209 if (\in_array($form, [self::NFC, self::NFKC], true)) {
210 normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
211 } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) {
212 throw new InvalidArgumentException('Unsupported normalization form.');
213 } elseif (!normalizer_is_normalized($str->string, $form)) {
214 $str->string = normalizer_normalize($str->string, $form);
215 $str->ignoreCase = null;
216 }
217
218 return $str;
219 }
220
221 public function prepend(string ...$prefix): static
222 {
223 $str = clone $this;
224 $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
225
226 if (normalizer_is_normalized($str->string)) {
227 return $str;
228 }
229
230 if (false === $string = normalizer_normalize($str->string)) {
231 throw new InvalidArgumentException('Invalid UTF-8 string.');
232 }
233
234 $str->string = $string;
235
236 return $str;
237 }
238
239 public function replace(string $from, string $to): static
240 {
241 $str = clone $this;
242 normalizer_is_normalized($from) ?: $from = normalizer_normalize($from);
243
244 if ('' !== $from && false !== $from) {
245 $tail = $str->string;
246 $result = '';
247 $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
248
249 while ('' !== $tail && false !== $i = $indexOf($tail, $from)) {
250 $slice = grapheme_substr($tail, 0, $i);
251 $result .= $slice.$to;
252 $tail = substr($tail, \strlen($slice) + \strlen($from));
253 }
254
255 $str->string = $result.$tail;
256
257 if (normalizer_is_normalized($str->string)) {
258 return $str;
259 }
260
261 if (false === $string = normalizer_normalize($str->string)) {
262 throw new InvalidArgumentException('Invalid UTF-8 string.');
263 }
264
265 $str->string = $string;
266 }
267
268 return $str;
269 }
270
271 public function replaceMatches(string $fromRegexp, string|callable $to): static
272 {
273 $str = parent::replaceMatches($fromRegexp, $to);
274 normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
275
276 return $str;
277 }
278
279 public function slice(int $start = 0, ?int $length = null): static
280 {
281 $str = clone $this;
282
283 $str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
284
285 return $str;
286 }
287
288 public function splice(string $replacement, int $start = 0, ?int $length = null): static
289 {
290 $str = clone $this;
291
292 $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
293 $length = $length ? \strlen(grapheme_substr($this->string, $start, $length)) : $length;
294 $str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647);
295
296 if (normalizer_is_normalized($str->string)) {
297 return $str;
298 }
299
300 if (false === $string = normalizer_normalize($str->string)) {
301 throw new InvalidArgumentException('Invalid UTF-8 string.');
302 }
303
304 $str->string = $string;
305
306 return $str;
307 }
308
309 public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
310 {
311 if (1 > $limit ??= 2147483647) {
312 throw new InvalidArgumentException('Split limit must be a positive integer.');
313 }
314
315 if ('' === $delimiter) {
316 throw new InvalidArgumentException('Split delimiter is empty.');
317 }
318
319 if (null !== $flags) {
320 return parent::split($delimiter.'u', $limit, $flags);
321 }
322
323 normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter);
324
325 if (false === $delimiter) {
326 throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.');
327 }
328
329 $str = clone $this;
330 $tail = $this->string;
331 $chunks = [];
332 $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
333
334 while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) {
335 $str->string = grapheme_substr($tail, 0, $i);
336 $chunks[] = clone $str;
337 $tail = substr($tail, \strlen($str->string) + \strlen($delimiter));
338 --$limit;
339 }
340
341 $str->string = $tail;
342 $chunks[] = clone $str;
343
344 return $chunks;
345 }
346
347 public function startsWith(string|iterable|AbstractString $prefix): bool
348 {
349 if ($prefix instanceof AbstractString) {
350 $prefix = $prefix->string;
351 } elseif (!\is_string($prefix)) {
352 return parent::startsWith($prefix);
353 }
354
355 $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
356 normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form);
357
358 if ('' === $prefix || false === $prefix) {
359 return false;
360 }
361
362 if (false === $grapheme = grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES)) {
363 $grapheme = '';
364 }
365
366 if ($this->ignoreCase) {
367 return 0 === mb_stripos($grapheme, $prefix, 0, 'UTF-8');
368 }
369
370 return $prefix === $grapheme;
371 }
372
373 public function trimPrefix($prefix): static
374 {
375 if (\is_array($prefix) || $prefix instanceof \Traversable) {
376 return parent::trimPrefix($prefix);
377 }
378
379 if ($prefix instanceof AbstractString) {
380 $prefix = $prefix->string;
381 } else {
382 $prefix = (string) $prefix;
383 }
384
385 if (!normalizer_is_normalized($prefix, \Normalizer::NFC)) {
386 $prefix = normalizer_normalize($prefix, \Normalizer::NFC);
387 }
388
389 return parent::trimPrefix($prefix);
390 }
391
392 public function trimSuffix($suffix): static
393 {
394 if (\is_array($suffix) || $suffix instanceof \Traversable) {
395 return parent::trimSuffix($suffix);
396 }
397
398 if ($suffix instanceof AbstractString) {
399 $suffix = $suffix->string;
400 } else {
401 $suffix = (string) $suffix;
402 }
403
404 if (!normalizer_is_normalized($suffix, \Normalizer::NFC)) {
405 $suffix = normalizer_normalize($suffix, \Normalizer::NFC);
406 }
407
408 return parent::trimSuffix($suffix);
409 }
410
411 public function __unserialize(array $data): void
412 {
413 if ($wakeup = self::class !== (new \ReflectionMethod($this, '__wakeup'))->class && self::class === (new \ReflectionMethod($this, '__unserialize'))->class) {
414 trigger_deprecation('symfony/string', '7.4', 'Implementing "%s::__wakeup()" is deprecated, use "__unserialize()" instead.', get_debug_type($this));
415 }
416
417 if (($data['string'] ?? null) instanceof \Stringable || ($data["\0*\0string"] ?? null) instanceof \Stringable) {
418 throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
419 }
420
421 try {
422 if (\in_array(array_keys($data), [['string'], ["\0*\0string"]], true)) {
423 $this->string = $data['string'] ?? $data["\0*\0string"];
424
425 if ($wakeup) {
426 $this->__wakeup();
427 }
428
429 return;
430 }
431
432 trigger_deprecation('symfony/string', '7.4', 'Passing more than just key "string" to "%s::__unserialize()" is deprecated, populate properties in "%s::__unserialize()" instead.', self::class, get_debug_type($this));
433
434 \Closure::bind(function ($data) use ($wakeup) {
435 foreach ($data as $key => $value) {
436 $this->{("\0" === $key[0] ?? '') ? substr($key, 1 + strrpos($key, "\0")) : $key} = $value;
437 }
438
439 if ($wakeup) {
440 $this->__wakeup();
441 }
442 }, $this, static::class)($data);
443 } finally {
444 if (!$wakeup) {
445 normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
446 }
447 }
448 }
449
450 /**
451 * @deprecated since Symfony 7.4, will be replaced by `__unserialize()` in 8.0
452 */
453 public function __wakeup(): void
454 {
455 trigger_deprecation('symfony/string', '7.4', 'Calling "%s::__wakeup()" is deprecated, use "__unserialize()" instead.', get_debug_type($this));
456
457 if (!\is_string($this->string)) {
458 throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
459 }
460
461 normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
462 }
463
464 public function __clone()
465 {
466 if (null === $this->ignoreCase) {
467 normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
468 }
469
470 $this->ignoreCase = false;
471 }
472 }