UnicodeString.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\String;
  11. use Symfony\Component\String\Exception\ExceptionInterface;
  12. use Symfony\Component\String\Exception\InvalidArgumentException;
  13. /**
  14. * Represents a string of Unicode grapheme clusters encoded as UTF-8.
  15. *
  16. * A letter followed by combining characters (accents typically) form what Unicode defines
  17. * as a grapheme cluster: a character as humans mean it in written texts. This class knows
  18. * about the concept and won't split a letter apart from its combining accents. It also
  19. * ensures all string comparisons happen on their canonically-composed representation,
  20. * ignoring e.g. the order in which accents are listed when a letter has many of them.
  21. *
  22. * @see https://unicode.org/reports/tr15/
  23. *
  24. * @author Nicolas Grekas <p@tchwork.com>
  25. * @author Hugo Hamon <hugohamon@neuf.fr>
  26. *
  27. * @throws ExceptionInterface
  28. */
  29. class UnicodeString extends AbstractUnicodeString
  30. {
  31. public function __construct(string $string = '')
  32. {
  33. if ('' === $string || normalizer_is_normalized($this->string = $string)) {
  34. return;
  35. }
  36. if (false === $string = normalizer_normalize($string)) {
  37. throw new InvalidArgumentException('Invalid UTF-8 string.');
  38. }
  39. $this->string = $string;
  40. }
  41. public function append(string ...$suffix): static
  42. {
  43. $str = clone $this;
  44. $str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix));
  45. if (normalizer_is_normalized($str->string)) {
  46. return $str;
  47. }
  48. if (false === $string = normalizer_normalize($str->string)) {
  49. throw new InvalidArgumentException('Invalid UTF-8 string.');
  50. }
  51. $str->string = $string;
  52. return $str;
  53. }
  54. public function chunk(int $length = 1): array
  55. {
  56. if (1 > $length) {
  57. throw new InvalidArgumentException('The chunk length must be greater than zero.');
  58. }
  59. if ('' === $this->string) {
  60. return [];
  61. }
  62. $rx = '/(';
  63. while (65535 < $length) {
  64. $rx .= '\X{65535}';
  65. $length -= 65535;
  66. }
  67. $rx .= '\X{'.$length.'})/u';
  68. $str = clone $this;
  69. $chunks = [];
  70. foreach (preg_split($rx, $this->string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY) as $chunk) {
  71. $str->string = $chunk;
  72. $chunks[] = clone $str;
  73. }
  74. return $chunks;
  75. }
  76. public function endsWith(string|iterable|AbstractString $suffix): bool
  77. {
  78. if ($suffix instanceof AbstractString) {
  79. $suffix = $suffix->string;
  80. } elseif (!\is_string($suffix)) {
  81. return parent::endsWith($suffix);
  82. }
  83. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  84. normalizer_is_normalized($suffix, $form) ?: $suffix = normalizer_normalize($suffix, $form);
  85. if ('' === $suffix || false === $suffix) {
  86. return false;
  87. }
  88. if ($this->ignoreCase) {
  89. return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8');
  90. }
  91. return $suffix === grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix));
  92. }
  93. public function equalsTo(string|iterable|AbstractString $string): bool
  94. {
  95. if ($string instanceof AbstractString) {
  96. $string = $string->string;
  97. } elseif (!\is_string($string)) {
  98. return parent::equalsTo($string);
  99. }
  100. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  101. normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form);
  102. if ('' !== $string && false !== $string && $this->ignoreCase) {
  103. return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8');
  104. }
  105. return $string === $this->string;
  106. }
  107. public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int
  108. {
  109. if ($needle instanceof AbstractString) {
  110. $needle = $needle->string;
  111. } elseif (!\is_string($needle)) {
  112. return parent::indexOf($needle, $offset);
  113. }
  114. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  115. normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
  116. if ('' === $needle || false === $needle) {
  117. return null;
  118. }
  119. try {
  120. $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset);
  121. } catch (\ValueError) {
  122. return null;
  123. }
  124. return false === $i ? null : $i;
  125. }
  126. public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int
  127. {
  128. if ($needle instanceof AbstractString) {
  129. $needle = $needle->string;
  130. } elseif (!\is_string($needle)) {
  131. return parent::indexOfLast($needle, $offset);
  132. }
  133. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  134. normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
  135. if ('' === $needle || false === $needle) {
  136. return null;
  137. }
  138. $string = $this->string;
  139. if (0 > $offset) {
  140. // workaround https://bugs.php.net/74264
  141. if (0 > $offset += grapheme_strlen($needle)) {
  142. $string = grapheme_substr($string, 0, $offset);
  143. }
  144. $offset = 0;
  145. }
  146. $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset);
  147. return false === $i ? null : $i;
  148. }
  149. public function join(array $strings, ?string $lastGlue = null): static
  150. {
  151. $str = parent::join($strings, $lastGlue);
  152. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  153. return $str;
  154. }
  155. public function length(): int
  156. {
  157. return grapheme_strlen($this->string);
  158. }
  159. public function normalize(int $form = self::NFC): static
  160. {
  161. $str = clone $this;
  162. if (\in_array($form, [self::NFC, self::NFKC], true)) {
  163. normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
  164. } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) {
  165. throw new InvalidArgumentException('Unsupported normalization form.');
  166. } elseif (!normalizer_is_normalized($str->string, $form)) {
  167. $str->string = normalizer_normalize($str->string, $form);
  168. $str->ignoreCase = null;
  169. }
  170. return $str;
  171. }
  172. public function prepend(string ...$prefix): static
  173. {
  174. $str = clone $this;
  175. $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
  176. if (normalizer_is_normalized($str->string)) {
  177. return $str;
  178. }
  179. if (false === $string = normalizer_normalize($str->string)) {
  180. throw new InvalidArgumentException('Invalid UTF-8 string.');
  181. }
  182. $str->string = $string;
  183. return $str;
  184. }
  185. public function replace(string $from, string $to): static
  186. {
  187. $str = clone $this;
  188. normalizer_is_normalized($from) ?: $from = normalizer_normalize($from);
  189. if ('' !== $from && false !== $from) {
  190. $tail = $str->string;
  191. $result = '';
  192. $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
  193. while ('' !== $tail && false !== $i = $indexOf($tail, $from)) {
  194. $slice = grapheme_substr($tail, 0, $i);
  195. $result .= $slice.$to;
  196. $tail = substr($tail, \strlen($slice) + \strlen($from));
  197. }
  198. $str->string = $result.$tail;
  199. if (normalizer_is_normalized($str->string)) {
  200. return $str;
  201. }
  202. if (false === $string = normalizer_normalize($str->string)) {
  203. throw new InvalidArgumentException('Invalid UTF-8 string.');
  204. }
  205. $str->string = $string;
  206. }
  207. return $str;
  208. }
  209. public function replaceMatches(string $fromRegexp, string|callable $to): static
  210. {
  211. $str = parent::replaceMatches($fromRegexp, $to);
  212. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  213. return $str;
  214. }
  215. public function slice(int $start = 0, ?int $length = null): static
  216. {
  217. $str = clone $this;
  218. $str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
  219. return $str;
  220. }
  221. public function splice(string $replacement, int $start = 0, ?int $length = null): static
  222. {
  223. $str = clone $this;
  224. $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
  225. $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? 2147483647)) : $length;
  226. $str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647);
  227. if (normalizer_is_normalized($str->string)) {
  228. return $str;
  229. }
  230. if (false === $string = normalizer_normalize($str->string)) {
  231. throw new InvalidArgumentException('Invalid UTF-8 string.');
  232. }
  233. $str->string = $string;
  234. return $str;
  235. }
  236. public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
  237. {
  238. if (1 > $limit ??= 2147483647) {
  239. throw new InvalidArgumentException('Split limit must be a positive integer.');
  240. }
  241. if ('' === $delimiter) {
  242. throw new InvalidArgumentException('Split delimiter is empty.');
  243. }
  244. if (null !== $flags) {
  245. return parent::split($delimiter.'u', $limit, $flags);
  246. }
  247. normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter);
  248. if (false === $delimiter) {
  249. throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.');
  250. }
  251. $str = clone $this;
  252. $tail = $this->string;
  253. $chunks = [];
  254. $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
  255. while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) {
  256. $str->string = grapheme_substr($tail, 0, $i);
  257. $chunks[] = clone $str;
  258. $tail = substr($tail, \strlen($str->string) + \strlen($delimiter));
  259. --$limit;
  260. }
  261. $str->string = $tail;
  262. $chunks[] = clone $str;
  263. return $chunks;
  264. }
  265. public function startsWith(string|iterable|AbstractString $prefix): bool
  266. {
  267. if ($prefix instanceof AbstractString) {
  268. $prefix = $prefix->string;
  269. } elseif (!\is_string($prefix)) {
  270. return parent::startsWith($prefix);
  271. }
  272. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  273. normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form);
  274. if ('' === $prefix || false === $prefix) {
  275. return false;
  276. }
  277. if ($this->ignoreCase) {
  278. return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8');
  279. }
  280. return $prefix === grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES);
  281. }
  282. /**
  283. * @return void
  284. */
  285. public function __wakeup()
  286. {
  287. if (!\is_string($this->string)) {
  288. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  289. }
  290. normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
  291. }
  292. public function __clone()
  293. {
  294. if (null === $this->ignoreCase) {
  295. normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
  296. }
  297. $this->ignoreCase = false;
  298. }
  299. }