Debian Codegraph @

vendor/symfony/string/AbstractString.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 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 doesn't care about the exact variant it deals with.
24 *
25 * @author Nicolas Grekas <[email protected]>
26 * @author Hugo Hamon <[email protected]>
27 *
28 * @throws ExceptionInterface
29 */
30 abstract class AbstractString implements \Stringable, \JsonSerializable
31 {
32 public const PREG_PATTERN_ORDER = \PREG_PATTERN_ORDER;
33 public const PREG_SET_ORDER = \PREG_SET_ORDER;
34 public const PREG_OFFSET_CAPTURE = \PREG_OFFSET_CAPTURE;
35 public const PREG_UNMATCHED_AS_NULL = \PREG_UNMATCHED_AS_NULL;
36
37 public const PREG_SPLIT = 0;
38 public const PREG_SPLIT_NO_EMPTY = \PREG_SPLIT_NO_EMPTY;
39 public const PREG_SPLIT_DELIM_CAPTURE = \PREG_SPLIT_DELIM_CAPTURE;
40 public const PREG_SPLIT_OFFSET_CAPTURE = \PREG_SPLIT_OFFSET_CAPTURE;
41
42 protected string $string = '';
43 protected ?bool $ignoreCase = false;
44
45 abstract public function __construct(string $string = '');
46
47 /**
48 * Unwraps instances of AbstractString back to strings.
49 *
50 * @return string[]|array
51 */
52 public static function unwrap(array $values): array
53 {
54 foreach ($values as $k => $v) {
55 if ($v instanceof self) {
56 $values[$k] = $v->__toString();
57 } elseif (\is_array($v) && $values[$k] !== $v = static::unwrap($v)) {
58 $values[$k] = $v;
59 }
60 }
61
62 return $values;
63 }
64
65 /**
66 * Wraps (and normalizes) strings in instances of AbstractString.
67 *
68 * @return static[]|array
69 */
70 public static function wrap(array $values): array
71 {
72 $i = 0;
73 $keys = null;
74
75 foreach ($values as $k => $v) {
76 if (\is_string($k) && '' !== $k && $k !== $j = (string) new static($k)) {
77 $keys ??= array_keys($values);
78 $keys[$i] = $j;
79 }
80
81 if (\is_string($v)) {
82 $values[$k] = new static($v);
83 } elseif (\is_array($v) && $values[$k] !== $v = static::wrap($v)) {
84 $values[$k] = $v;
85 }
86
87 ++$i;
88 }
89
90 return null !== $keys ? array_combine($keys, $values) : $values;
91 }
92
93 /**
94 * @param string|string[] $needle
95 */
96 public function after(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
97 {
98 $str = clone $this;
99 $i = \PHP_INT_MAX;
100
101 if (\is_string($needle)) {
102 $needle = [$needle];
103 }
104
105 foreach ($needle as $n) {
106 $n = (string) $n;
107 $j = $this->indexOf($n, $offset);
108
109 if (null !== $j && $j < $i) {
110 $i = $j;
111 $str->string = $n;
112 }
113 }
114
115 if (\PHP_INT_MAX === $i) {
116 return $str;
117 }
118
119 if (!$includeNeedle) {
120 $i += $str->length();
121 }
122
123 return $this->slice($i);
124 }
125
126 /**
127 * @param string|string[] $needle
128 */
129 public function afterLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
130 {
131 $str = clone $this;
132 $i = null;
133
134 if (\is_string($needle)) {
135 $needle = [$needle];
136 }
137
138 foreach ($needle as $n) {
139 $n = (string) $n;
140 $j = $this->indexOfLast($n, $offset);
141
142 if (null !== $j && $j >= $i) {
143 $i = $offset = $j;
144 $str->string = $n;
145 }
146 }
147
148 if (null === $i) {
149 return $str;
150 }
151
152 if (!$includeNeedle) {
153 $i += $str->length();
154 }
155
156 return $this->slice($i);
157 }
158
159 abstract public function append(string ...$suffix): static;
160
161 /**
162 * @param string|string[] $needle
163 */
164 public function before(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
165 {
166 $str = clone $this;
167 $i = \PHP_INT_MAX;
168
169 if (\is_string($needle)) {
170 $needle = [$needle];
171 }
172
173 foreach ($needle as $n) {
174 $n = (string) $n;
175 $j = $this->indexOf($n, $offset);
176
177 if (null !== $j && $j < $i) {
178 $i = $j;
179 $str->string = $n;
180 }
181 }
182
183 if (\PHP_INT_MAX === $i) {
184 return $str;
185 }
186
187 if ($includeNeedle) {
188 $i += $str->length();
189 }
190
191 return $this->slice(0, $i);
192 }
193
194 /**
195 * @param string|string[] $needle
196 */
197 public function beforeLast(string|iterable $needle, bool $includeNeedle = false, int $offset = 0): static
198 {
199 $str = clone $this;
200 $i = null;
201
202 if (\is_string($needle)) {
203 $needle = [$needle];
204 }
205
206 foreach ($needle as $n) {
207 $n = (string) $n;
208 $j = $this->indexOfLast($n, $offset);
209
210 if (null !== $j && $j >= $i) {
211 $i = $offset = $j;
212 $str->string = $n;
213 }
214 }
215
216 if (null === $i) {
217 return $str;
218 }
219
220 if ($includeNeedle) {
221 $i += $str->length();
222 }
223
224 return $this->slice(0, $i);
225 }
226
227 /**
228 * @return int[]
229 */
230 public function bytesAt(int $offset): array
231 {
232 $str = $this->slice($offset, 1);
233
234 return '' === $str->string ? [] : array_values(unpack('C*', $str->string));
235 }
236
237 abstract public function camel(): static;
238
239 /**
240 * @return static[]
241 */
242 abstract public function chunk(int $length = 1): array;
243
244 public function collapseWhitespace(): static
245 {
246 $str = clone $this;
247 $str->string = trim(preg_replace("/(?:[ \n\r\t\x0C]{2,}+|[\n\r\t\x0C])/", ' ', $str->string), " \n\r\t\x0C");
248
249 return $str;
250 }
251
252 /**
253 * @param string|string[] $needle
254 */
255 public function containsAny(string|iterable $needle): bool
256 {
257 return null !== $this->indexOf($needle);
258 }
259
260 /**
261 * @param string|string[] $suffix
262 */
263 public function endsWith(string|iterable $suffix): bool
264 {
265 if (\is_string($suffix)) {
266 throw new \TypeError(\sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
267 }
268
269 foreach ($suffix as $s) {
270 if ($this->endsWith((string) $s)) {
271 return true;
272 }
273 }
274
275 return false;
276 }
277
278 public function ensureEnd(string $suffix): static
279 {
280 if (!$this->endsWith($suffix)) {
281 return $this->append($suffix);
282 }
283
284 $suffix = preg_quote($suffix);
285 $regex = '{('.$suffix.')(?:'.$suffix.')++$}D';
286
287 return $this->replaceMatches($regex.($this->ignoreCase ? 'i' : ''), '$1');
288 }
289
290 public function ensureStart(string $prefix): static
291 {
292 $prefix = new static($prefix);
293
294 if (!$this->startsWith($prefix)) {
295 return $this->prepend($prefix);
296 }
297
298 $str = clone $this;
299 $i = $prefixLen = $prefix->length();
300
301 while ($this->indexOf($prefix, $i) === $i) {
302 $str = $str->slice($prefixLen);
303 $i += $prefixLen;
304 }
305
306 return $str;
307 }
308
309 /**
310 * @param string|string[] $string
311 */
312 public function equalsTo(string|iterable $string): bool
313 {
314 if (\is_string($string)) {
315 throw new \TypeError(\sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
316 }
317
318 foreach ($string as $s) {
319 if ($this->equalsTo((string) $s)) {
320 return true;
321 }
322 }
323
324 return false;
325 }
326
327 abstract public function folded(): static;
328
329 public function ignoreCase(): static
330 {
331 $str = clone $this;
332 $str->ignoreCase = true;
333
334 return $str;
335 }
336
337 /**
338 * @param string|string[] $needle
339 */
340 public function indexOf(string|iterable $needle, int $offset = 0): ?int
341 {
342 if (\is_string($needle)) {
343 throw new \TypeError(\sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
344 }
345
346 $i = \PHP_INT_MAX;
347
348 foreach ($needle as $n) {
349 $j = $this->indexOf((string) $n, $offset);
350
351 if (null !== $j && $j < $i) {
352 $i = $j;
353 }
354 }
355
356 return \PHP_INT_MAX === $i ? null : $i;
357 }
358
359 /**
360 * @param string|string[] $needle
361 */
362 public function indexOfLast(string|iterable $needle, int $offset = 0): ?int
363 {
364 if (\is_string($needle)) {
365 throw new \TypeError(\sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
366 }
367
368 $i = null;
369
370 foreach ($needle as $n) {
371 $j = $this->indexOfLast((string) $n, $offset);
372
373 if (null !== $j && $j >= $i) {
374 $i = $offset = $j;
375 }
376 }
377
378 return $i;
379 }
380
381 public function isEmpty(): bool
382 {
383 return '' === $this->string;
384 }
385
386 abstract public function join(array $strings, ?string $lastGlue = null): static;
387
388 public function jsonSerialize(): string
389 {
390 return $this->string;
391 }
392
393 abstract public function length(): int;
394
395 abstract public function lower(): static;
396
397 /**
398 * Matches the string using a regular expression.
399 *
400 * Pass PREG_PATTERN_ORDER or PREG_SET_ORDER as $flags to get all occurrences matching the regular expression.
401 *
402 * @return array All matches in a multi-dimensional array ordered according to flags
403 */
404 abstract public function match(string $regexp, int $flags = 0, int $offset = 0): array;
405
406 abstract public function padBoth(int $length, string $padStr = ' '): static;
407
408 abstract public function padEnd(int $length, string $padStr = ' '): static;
409
410 abstract public function padStart(int $length, string $padStr = ' '): static;
411
412 abstract public function prepend(string ...$prefix): static;
413
414 public function repeat(int $multiplier): static
415 {
416 if (0 > $multiplier) {
417 throw new InvalidArgumentException(\sprintf('Multiplier must be positive, %d given.', $multiplier));
418 }
419
420 $str = clone $this;
421 $str->string = str_repeat($str->string, $multiplier);
422
423 return $str;
424 }
425
426 abstract public function replace(string $from, string $to): static;
427
428 abstract public function replaceMatches(string $fromRegexp, string|callable $to): static;
429
430 abstract public function reverse(): static;
431
432 abstract public function slice(int $start = 0, ?int $length = null): static;
433
434 abstract public function snake(): static;
435
436 public function kebab(): static
437 {
438 return $this->snake()->replace('_', '-');
439 }
440
441 public function pascal(): static
442 {
443 return $this->camel()->title();
444 }
445
446 abstract public function splice(string $replacement, int $start = 0, ?int $length = null): static;
447
448 /**
449 * @return static[]
450 */
451 public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
452 {
453 if (null === $flags) {
454 throw new \TypeError('Split behavior when $flags is null must be implemented by child classes.');
455 }
456
457 if ($this->ignoreCase) {
458 $delimiter .= 'i';
459 }
460
461 set_error_handler(static fn ($t, $m) => throw new InvalidArgumentException($m));
462
463 try {
464 if (false === $chunks = preg_split($delimiter, $this->string, $limit, $flags)) {
465 throw new RuntimeException('Splitting failed with error: '.preg_last_error_msg());
466 }
467 } finally {
468 restore_error_handler();
469 }
470
471 $str = clone $this;
472
473 if (self::PREG_SPLIT_OFFSET_CAPTURE & $flags) {
474 foreach ($chunks as &$chunk) {
475 $str->string = $chunk[0];
476 $chunk[0] = clone $str;
477 }
478 } else {
479 foreach ($chunks as &$chunk) {
480 $str->string = $chunk;
481 $chunk = clone $str;
482 }
483 }
484
485 return $chunks;
486 }
487
488 /**
489 * @param string|string[] $prefix
490 */
491 public function startsWith(string|iterable $prefix): bool
492 {
493 if (\is_string($prefix)) {
494 throw new \TypeError(\sprintf('Method "%s()" must be overridden by class "%s" to deal with non-iterable values.', __FUNCTION__, static::class));
495 }
496
497 foreach ($prefix as $prefix) {
498 if ($this->startsWith((string) $prefix)) {
499 return true;
500 }
501 }
502
503 return false;
504 }
505
506 abstract public function title(bool $allWords = false): static;
507
508 public function toByteString(?string $toEncoding = null): ByteString
509 {
510 $b = new ByteString();
511
512 $toEncoding = \in_array($toEncoding, ['utf8', 'utf-8', 'UTF8'], true) ? 'UTF-8' : $toEncoding;
513
514 if (null === $toEncoding || $toEncoding === $fromEncoding = $this instanceof AbstractUnicodeString || preg_match('//u', $b->string) ? 'UTF-8' : 'Windows-1252') {
515 $b->string = $this->string;
516
517 return $b;
518 }
519
520 try {
521 $b->string = mb_convert_encoding($this->string, $toEncoding, 'UTF-8');
522 } catch (\ValueError $e) {
523 if (!\function_exists('iconv')) {
524 throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
525 }
526
527 $b->string = iconv('UTF-8', $toEncoding, $this->string);
528 }
529
530 return $b;
531 }
532
533 public function toCodePointString(): CodePointString
534 {
535 return new CodePointString($this->string);
536 }
537
538 public function toString(): string
539 {
540 return $this->string;
541 }
542
543 public function toUnicodeString(): UnicodeString
544 {
545 return new UnicodeString($this->string);
546 }
547
548 abstract public function trim(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
549
550 abstract public function trimEnd(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
551
552 /**
553 * @param string|string[] $prefix
554 */
555 public function trimPrefix($prefix): static
556 {
557 if (\is_array($prefix) || $prefix instanceof \Traversable) { // don't use is_iterable(), it's slow
558 foreach ($prefix as $s) {
559 $t = $this->trimPrefix($s);
560
561 if ($t->string !== $this->string) {
562 return $t;
563 }
564 }
565
566 return clone $this;
567 }
568
569 $str = clone $this;
570
571 if ($prefix instanceof self) {
572 $prefix = $prefix->string;
573 } else {
574 $prefix = (string) $prefix;
575 }
576
577 if ('' !== $prefix && \strlen($this->string) >= \strlen($prefix) && 0 === substr_compare($this->string, $prefix, 0, \strlen($prefix), $this->ignoreCase)) {
578 $str->string = substr($this->string, \strlen($prefix));
579 }
580
581 return $str;
582 }
583
584 abstract public function trimStart(string $chars = " \t\n\r\0\x0B\x0C\u{A0}\u{FEFF}"): static;
585
586 /**
587 * @param string|string[] $suffix
588 */
589 public function trimSuffix($suffix): static
590 {
591 if (\is_array($suffix) || $suffix instanceof \Traversable) { // don't use is_iterable(), it's slow
592 foreach ($suffix as $s) {
593 $t = $this->trimSuffix($s);
594
595 if ($t->string !== $this->string) {
596 return $t;
597 }
598 }
599
600 return clone $this;
601 }
602
603 $str = clone $this;
604
605 if ($suffix instanceof self) {
606 $suffix = $suffix->string;
607 } else {
608 $suffix = (string) $suffix;
609 }
610
611 if ('' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase)) {
612 $str->string = substr($this->string, 0, -\strlen($suffix));
613 }
614
615 return $str;
616 }
617
618 public function truncate(int $length, string $ellipsis = '', bool|TruncateMode $cut = TruncateMode::Char): static
619 {
620 $stringLength = $this->length();
621
622 if ($stringLength <= $length) {
623 return clone $this;
624 }
625
626 $ellipsisLength = '' !== $ellipsis ? (new static($ellipsis))->length() : 0;
627
628 if ($length < $ellipsisLength) {
629 $ellipsisLength = 0;
630 }
631
632 $desiredLength = $length;
633 if (TruncateMode::WordAfter === $cut || !$cut) {
634 if (null === $length = $this->indexOf([' ', "\r", "\n", "\t"], ($length ?: 1) - 1)) {
635 return clone $this;
636 }
637
638 $length += $ellipsisLength;
639 } elseif (TruncateMode::WordBefore === $cut && null !== $this->indexOf([' ', "\r", "\n", "\t"], ($length ?: 1) - 1)) {
640 $length += $ellipsisLength;
641 }
642
643 $str = $this->slice(0, $length - $ellipsisLength);
644
645 if (TruncateMode::WordBefore === $cut) {
646 if (0 === $ellipsisLength && $desiredLength === $this->indexOf([' ', "\r", "\n", "\t"], $length)) {
647 return $str;
648 }
649
650 $str = $str->beforeLast([' ', "\r", "\n", "\t"]);
651 }
652
653 return $ellipsisLength ? $str->trimEnd()->append($ellipsis) : $str;
654 }
655
656 abstract public function upper(): static;
657
658 /**
659 * Returns the printable length on a terminal.
660 */
661 abstract public function width(bool $ignoreAnsiDecoration = true): int;
662
663 public function wordwrap(int $width = 75, string $break = "\n", bool $cut = false): static
664 {
665 $lines = '' !== $break ? $this->split($break) : [clone $this];
666 $chars = [];
667 $mask = '';
668
669 if (1 === \count($lines) && '' === $lines[0]->string) {
670 return $lines[0];
671 }
672
673 foreach ($lines as $i => $line) {
674 if ($i) {
675 $chars[] = $break;
676 $mask .= '#';
677 }
678
679 foreach ($line->chunk() as $char) {
680 $chars[] = $char->string;
681 $mask .= ' ' === $char->string ? ' ' : '?';
682 }
683 }
684
685 $string = '';
686 $j = 0;
687 $b = $i = -1;
688 $mask = wordwrap($mask, $width, '#', $cut);
689
690 while (false !== $b = strpos($mask, '#', $b + 1)) {
691 for (++$i; $i < $b; ++$i) {
692 $string .= $chars[$j];
693 unset($chars[$j++]);
694 }
695
696 if ($break === $chars[$j] || ' ' === $chars[$j]) {
697 unset($chars[$j++]);
698 }
699
700 $string .= $break;
701 }
702
703 $str = clone $this;
704 $str->string = $string.implode('', $chars);
705
706 return $str;
707 }
708
709 public function __serialize(): array
710 {
711 if (self::class === (new \ReflectionMethod($this, '__sleep'))->class || self::class !== (new \ReflectionMethod($this, '__serialize'))->class) {
712 return ['string' => $this->string];
713 }
714
715 trigger_deprecation('symfony/string', '7.4', 'Implementing "%s::__sleep()" is deprecated, use "__serialize()" instead.', get_debug_type($this));
716
717 $data = [];
718 foreach ($this->__sleep() as $key) {
719 try {
720 if (($r = new \ReflectionProperty($this, $key))->isInitialized($this)) {
721 $data[$key] = $r->getValue($this);
722 }
723 } catch (\ReflectionException) {
724 $data[$key] = $this->$key;
725 }
726 }
727
728 return $data;
729 }
730
731 /**
732 * @deprecated since Symfony 7.4, will be replaced by `__unserialize()` in 8.0
733 */
734 public function __sleep(): array
735 {
736 trigger_deprecation('symfony/string', '7.4', 'Calling "%s::__sleep()" is deprecated, use "__serialize()" instead.', get_debug_type($this));
737
738 return ['string'];
739 }
740
741 public function __clone()
742 {
743 $this->ignoreCase = false;
744 }
745
746 public function __toString(): string
747 {
748 return $this->string;
749 }
750 }