UnicodeString.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. $this->string = normalizer_is_normalized($string) ? $string : normalizer_normalize($string);
  34. if (false === $this->string) {
  35. throw new InvalidArgumentException('Invalid UTF-8 string.');
  36. }
  37. }
  38. public function append(string ...$suffix): AbstractString
  39. {
  40. $str = clone $this;
  41. $str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix));
  42. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  43. if (false === $str->string) {
  44. throw new InvalidArgumentException('Invalid UTF-8 string.');
  45. }
  46. return $str;
  47. }
  48. public function chunk(int $length = 1): array
  49. {
  50. if (1 > $length) {
  51. throw new InvalidArgumentException('The chunk length must be greater than zero.');
  52. }
  53. if ('' === $this->string) {
  54. return [];
  55. }
  56. $rx = '/(';
  57. while (65535 < $length) {
  58. $rx .= '\X{65535}';
  59. $length -= 65535;
  60. }
  61. $rx .= '\X{'.$length.'})/u';
  62. $str = clone $this;
  63. $chunks = [];
  64. foreach (preg_split($rx, $this->string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $chunk) {
  65. $str->string = $chunk;
  66. $chunks[] = clone $str;
  67. }
  68. return $chunks;
  69. }
  70. public function endsWith($suffix): bool
  71. {
  72. if ($suffix instanceof AbstractString) {
  73. $suffix = $suffix->string;
  74. } elseif (\is_array($suffix) || $suffix instanceof \Traversable) {
  75. return parent::endsWith($suffix);
  76. } else {
  77. $suffix = (string) $suffix;
  78. }
  79. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  80. normalizer_is_normalized($suffix, $form) ?: $suffix = normalizer_normalize($suffix, $form);
  81. if ('' === $suffix || false === $suffix) {
  82. return false;
  83. }
  84. if ($this->ignoreCase) {
  85. return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8');
  86. }
  87. return $suffix === grapheme_extract($this->string, \strlen($suffix), GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix));
  88. }
  89. public function equalsTo($string): bool
  90. {
  91. if ($string instanceof AbstractString) {
  92. $string = $string->string;
  93. } elseif (\is_array($string) || $string instanceof \Traversable) {
  94. return parent::equalsTo($string);
  95. } else {
  96. $string = (string) $string;
  97. }
  98. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  99. normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form);
  100. if ('' !== $string && false !== $string && $this->ignoreCase) {
  101. return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8');
  102. }
  103. return $string === $this->string;
  104. }
  105. public function indexOf($needle, int $offset = 0): ?int
  106. {
  107. if ($needle instanceof AbstractString) {
  108. $needle = $needle->string;
  109. } elseif (\is_array($needle) || $needle instanceof \Traversable) {
  110. return parent::indexOf($needle, $offset);
  111. } else {
  112. $needle = (string) $needle;
  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. $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset);
  120. return false === $i ? null : $i;
  121. }
  122. public function indexOfLast($needle, int $offset = 0): ?int
  123. {
  124. if ($needle instanceof AbstractString) {
  125. $needle = $needle->string;
  126. } elseif (\is_array($needle) || $needle instanceof \Traversable) {
  127. return parent::indexOfLast($needle, $offset);
  128. } else {
  129. $needle = (string) $needle;
  130. }
  131. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  132. normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
  133. if ('' === $needle || false === $needle) {
  134. return null;
  135. }
  136. $string = $this->string;
  137. if (0 > $offset) {
  138. // workaround https://bugs.php.net/74264
  139. if (0 > $offset += grapheme_strlen($needle)) {
  140. $string = grapheme_substr($string, 0, $offset);
  141. }
  142. $offset = 0;
  143. }
  144. $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset);
  145. return false === $i ? null : $i;
  146. }
  147. public function join(array $strings, string $lastGlue = null): AbstractString
  148. {
  149. $str = parent::join($strings, $lastGlue);
  150. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  151. return $str;
  152. }
  153. public function length(): int
  154. {
  155. return grapheme_strlen($this->string);
  156. }
  157. /**
  158. * @return static
  159. */
  160. public function normalize(int $form = self::NFC): parent
  161. {
  162. $str = clone $this;
  163. if (\in_array($form, [self::NFC, self::NFKC], true)) {
  164. normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
  165. } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) {
  166. throw new InvalidArgumentException('Unsupported normalization form.');
  167. } elseif (!normalizer_is_normalized($str->string, $form)) {
  168. $str->string = normalizer_normalize($str->string, $form);
  169. $str->ignoreCase = null;
  170. }
  171. return $str;
  172. }
  173. public function prepend(string ...$prefix): AbstractString
  174. {
  175. $str = clone $this;
  176. $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
  177. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  178. if (false === $str->string) {
  179. throw new InvalidArgumentException('Invalid UTF-8 string.');
  180. }
  181. return $str;
  182. }
  183. public function replace(string $from, string $to): AbstractString
  184. {
  185. $str = clone $this;
  186. normalizer_is_normalized($from) ?: $from = normalizer_normalize($from);
  187. if ('' !== $from && false !== $from) {
  188. $tail = $str->string;
  189. $result = '';
  190. $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
  191. while (false !== $i = $indexOf($tail, $from)) {
  192. $slice = grapheme_substr($tail, 0, $i);
  193. $result .= $slice.$to;
  194. $tail = substr($tail, \strlen($slice) + \strlen($from));
  195. }
  196. $str->string = $result.$tail;
  197. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  198. if (false === $str->string) {
  199. throw new InvalidArgumentException('Invalid UTF-8 string.');
  200. }
  201. }
  202. return $str;
  203. }
  204. public function replaceMatches(string $fromRegexp, $to): AbstractString
  205. {
  206. $str = parent::replaceMatches($fromRegexp, $to);
  207. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  208. return $str;
  209. }
  210. public function slice(int $start = 0, int $length = null): AbstractString
  211. {
  212. $str = clone $this;
  213. $str->string = (string) grapheme_substr($this->string, $start, $length ?? \PHP_INT_MAX);
  214. return $str;
  215. }
  216. public function splice(string $replacement, int $start = 0, int $length = null): AbstractString
  217. {
  218. $str = clone $this;
  219. $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
  220. $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? \PHP_INT_MAX)) : $length;
  221. $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX);
  222. normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
  223. if (false === $str->string) {
  224. throw new InvalidArgumentException('Invalid UTF-8 string.');
  225. }
  226. return $str;
  227. }
  228. public function split(string $delimiter, int $limit = null, int $flags = null): array
  229. {
  230. if (1 > $limit = $limit ?? \PHP_INT_MAX) {
  231. throw new InvalidArgumentException('Split limit must be a positive integer.');
  232. }
  233. if ('' === $delimiter) {
  234. throw new InvalidArgumentException('Split delimiter is empty.');
  235. }
  236. if (null !== $flags) {
  237. return parent::split($delimiter.'u', $limit, $flags);
  238. }
  239. normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter);
  240. if (false === $delimiter) {
  241. throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.');
  242. }
  243. $str = clone $this;
  244. $tail = $this->string;
  245. $chunks = [];
  246. $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
  247. while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) {
  248. $str->string = grapheme_substr($tail, 0, $i);
  249. $chunks[] = clone $str;
  250. $tail = substr($tail, \strlen($str->string) + \strlen($delimiter));
  251. --$limit;
  252. }
  253. $str->string = $tail;
  254. $chunks[] = clone $str;
  255. return $chunks;
  256. }
  257. public function startsWith($prefix): bool
  258. {
  259. if ($prefix instanceof AbstractString) {
  260. $prefix = $prefix->string;
  261. } elseif (\is_array($prefix) || $prefix instanceof \Traversable) {
  262. return parent::startsWith($prefix);
  263. } else {
  264. $prefix = (string) $prefix;
  265. }
  266. $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
  267. normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form);
  268. if ('' === $prefix || false === $prefix) {
  269. return false;
  270. }
  271. if ($this->ignoreCase) {
  272. return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8');
  273. }
  274. return $prefix === grapheme_extract($this->string, \strlen($prefix), GRAPHEME_EXTR_MAXBYTES);
  275. }
  276. public function __wakeup()
  277. {
  278. normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
  279. }
  280. public function __clone()
  281. {
  282. if (null === $this->ignoreCase) {
  283. normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
  284. }
  285. $this->ignoreCase = false;
  286. }
  287. }