UnicodeString.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 (false === $grapheme = grapheme_extract($this->string, \strlen($suffix), \GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix))) {
  89. $grapheme = '';
  90. }
  91. if ($this->ignoreCase) {
  92. return 0 === mb_stripos($grapheme, $suffix, 0, 'UTF-8');
  93. }
  94. return $suffix === $grapheme;
  95. }
  96. public function equalsTo(string|iterable|AbstractString $string): bool
  97. {
  98. if ($string instanceof AbstractString) {
  99. $string = $string->string;
  100. } elseif (!\is_string($string)) {
  101. return parent::equalsTo($string);
  102. }
  103. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  104. normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form);
  105. if ('' !== $string && false !== $string && $this->ignoreCase) {
  106. return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8');
  107. }
  108. return $string === $this->string;
  109. }
  110. public function indexOf(string|iterable|AbstractString $needle, int $offset = 0): ?int
  111. {
  112. if ($needle instanceof AbstractString) {
  113. $needle = $needle->string;
  114. } elseif (!\is_string($needle)) {
  115. return parent::indexOf($needle, $offset);
  116. }
  117. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  118. normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
  119. if ('' === $needle || false === $needle) {
  120. return null;
  121. }
  122. try {
  123. $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset);
  124. } catch (\ValueError) {
  125. return null;
  126. }
  127. return false === $i ? null : $i;
  128. }
  129. public function indexOfLast(string|iterable|AbstractString $needle, int $offset = 0): ?int
  130. {
  131. if ($needle instanceof AbstractString) {
  132. $needle = $needle->string;
  133. } elseif (!\is_string($needle)) {
  134. return parent::indexOfLast($needle, $offset);
  135. }
  136. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  137. normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
  138. if ('' === $needle || false === $needle) {
  139. return null;
  140. }
  141. $string = $this->string;
  142. if (0 > $offset) {
  143. // workaround https://bugs.php.net/74264
  144. if (0 > $offset += grapheme_strlen($needle)) {
  145. $string = grapheme_substr($string, 0, $offset);
  146. }
  147. $offset = 0;
  148. }
  149. $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset);
  150. return false === $i ? null : $i;
  151. }
  152. public function join(array $strings, ?string $lastGlue = null): static
  153. {
  154. $str = parent::join($strings, $lastGlue);
  155. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  156. return $str;
  157. }
  158. public function length(): int
  159. {
  160. return grapheme_strlen($this->string);
  161. }
  162. public function normalize(int $form = self::NFC): static
  163. {
  164. $str = clone $this;
  165. if (\in_array($form, [self::NFC, self::NFKC], true)) {
  166. normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
  167. } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) {
  168. throw new InvalidArgumentException('Unsupported normalization form.');
  169. } elseif (!normalizer_is_normalized($str->string, $form)) {
  170. $str->string = normalizer_normalize($str->string, $form);
  171. $str->ignoreCase = null;
  172. }
  173. return $str;
  174. }
  175. public function prepend(string ...$prefix): static
  176. {
  177. $str = clone $this;
  178. $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
  179. if (normalizer_is_normalized($str->string)) {
  180. return $str;
  181. }
  182. if (false === $string = normalizer_normalize($str->string)) {
  183. throw new InvalidArgumentException('Invalid UTF-8 string.');
  184. }
  185. $str->string = $string;
  186. return $str;
  187. }
  188. public function replace(string $from, string $to): static
  189. {
  190. $str = clone $this;
  191. normalizer_is_normalized($from) ?: $from = normalizer_normalize($from);
  192. if ('' !== $from && false !== $from) {
  193. $tail = $str->string;
  194. $result = '';
  195. $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
  196. while ('' !== $tail && false !== $i = $indexOf($tail, $from)) {
  197. $slice = grapheme_substr($tail, 0, $i);
  198. $result .= $slice.$to;
  199. $tail = substr($tail, \strlen($slice) + \strlen($from));
  200. }
  201. $str->string = $result.$tail;
  202. if (normalizer_is_normalized($str->string)) {
  203. return $str;
  204. }
  205. if (false === $string = normalizer_normalize($str->string)) {
  206. throw new InvalidArgumentException('Invalid UTF-8 string.');
  207. }
  208. $str->string = $string;
  209. }
  210. return $str;
  211. }
  212. public function replaceMatches(string $fromRegexp, string|callable $to): static
  213. {
  214. $str = parent::replaceMatches($fromRegexp, $to);
  215. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  216. return $str;
  217. }
  218. public function slice(int $start = 0, ?int $length = null): static
  219. {
  220. $str = clone $this;
  221. $str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
  222. return $str;
  223. }
  224. public function splice(string $replacement, int $start = 0, ?int $length = null): static
  225. {
  226. $str = clone $this;
  227. $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
  228. $length = $length ? \strlen(grapheme_substr($this->string, $start, $length)) : $length;
  229. $str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647);
  230. if (normalizer_is_normalized($str->string)) {
  231. return $str;
  232. }
  233. if (false === $string = normalizer_normalize($str->string)) {
  234. throw new InvalidArgumentException('Invalid UTF-8 string.');
  235. }
  236. $str->string = $string;
  237. return $str;
  238. }
  239. public function split(string $delimiter, ?int $limit = null, ?int $flags = null): array
  240. {
  241. if (1 > $limit ??= 2147483647) {
  242. throw new InvalidArgumentException('Split limit must be a positive integer.');
  243. }
  244. if ('' === $delimiter) {
  245. throw new InvalidArgumentException('Split delimiter is empty.');
  246. }
  247. if (null !== $flags) {
  248. return parent::split($delimiter.'u', $limit, $flags);
  249. }
  250. normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter);
  251. if (false === $delimiter) {
  252. throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.');
  253. }
  254. $str = clone $this;
  255. $tail = $this->string;
  256. $chunks = [];
  257. $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
  258. while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) {
  259. $str->string = grapheme_substr($tail, 0, $i);
  260. $chunks[] = clone $str;
  261. $tail = substr($tail, \strlen($str->string) + \strlen($delimiter));
  262. --$limit;
  263. }
  264. $str->string = $tail;
  265. $chunks[] = clone $str;
  266. return $chunks;
  267. }
  268. public function startsWith(string|iterable|AbstractString $prefix): bool
  269. {
  270. if ($prefix instanceof AbstractString) {
  271. $prefix = $prefix->string;
  272. } elseif (!\is_string($prefix)) {
  273. return parent::startsWith($prefix);
  274. }
  275. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  276. normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form);
  277. if ('' === $prefix || false === $prefix) {
  278. return false;
  279. }
  280. if (false === $grapheme = grapheme_extract($this->string, \strlen($prefix), \GRAPHEME_EXTR_MAXBYTES)) {
  281. $grapheme = '';
  282. }
  283. if ($this->ignoreCase) {
  284. return 0 === mb_stripos($grapheme, $prefix, 0, 'UTF-8');
  285. }
  286. return $prefix === $grapheme;
  287. }
  288. public function trimPrefix($prefix): static
  289. {
  290. if (\is_array($prefix) || $prefix instanceof \Traversable) {
  291. return parent::trimPrefix($prefix);
  292. }
  293. if ($prefix instanceof AbstractString) {
  294. $prefix = $prefix->string;
  295. } else {
  296. $prefix = (string) $prefix;
  297. }
  298. if (!normalizer_is_normalized($prefix, \Normalizer::NFC)) {
  299. $prefix = normalizer_normalize($prefix, \Normalizer::NFC);
  300. }
  301. return parent::trimPrefix($prefix);
  302. }
  303. public function trimSuffix($suffix): static
  304. {
  305. if (\is_array($suffix) || $suffix instanceof \Traversable) {
  306. return parent::trimSuffix($suffix);
  307. }
  308. if ($suffix instanceof AbstractString) {
  309. $suffix = $suffix->string;
  310. } else {
  311. $suffix = (string) $suffix;
  312. }
  313. if (!normalizer_is_normalized($suffix, \Normalizer::NFC)) {
  314. $suffix = normalizer_normalize($suffix, \Normalizer::NFC);
  315. }
  316. return parent::trimSuffix($suffix);
  317. }
  318. public function __unserialize(array $data): void
  319. {
  320. $this->string = $data['string'] ?? $data["\0*\0string"];
  321. if (!\is_string($this->string)) {
  322. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  323. }
  324. normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
  325. }
  326. public function __clone()
  327. {
  328. if (null === $this->ignoreCase) {
  329. normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
  330. }
  331. $this->ignoreCase = false;
  332. }
  333. }