ByteString.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. use Symfony\Component\String\Exception\RuntimeException;
  14. /**
  15. * Represents a binary-safe string of bytes.
  16. *
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. * @author Hugo Hamon <hugohamon@neuf.fr>
  19. *
  20. * @throws ExceptionInterface
  21. */
  22. class ByteString extends AbstractString
  23. {
  24. private const ALPHABET_ALPHANUMERIC = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  25. /**
  26. * @param string $string
  27. */
  28. public function __construct($string = '')
  29. {
  30. $this->string = $string;
  31. }
  32. /*
  33. * The following method was derived from code of the Hack Standard Library (v4.40 - 2020-05-03)
  34. *
  35. * https://github.com/hhvm/hsl/blob/80a42c02f036f72a42f0415e80d6b847f4bf62d5/src/random/private.php#L16
  36. *
  37. * Code subject to the MIT license (https://github.com/hhvm/hsl/blob/master/LICENSE).
  38. *
  39. * Copyright (c) 2004-2020, Facebook, Inc. (https://www.facebook.com/)
  40. */
  41. /**
  42. * @param int $length
  43. * @param string|null $alphabet
  44. */
  45. public static function fromRandom($length = 16, $alphabet = null)
  46. {
  47. if ($length <= 0) {
  48. throw new InvalidArgumentException(sprintf('A strictly positive length is expected, "%d" given.', $length));
  49. }
  50. $alphabet = $alphabet ?? self::ALPHABET_ALPHANUMERIC;
  51. $alphabetSize = \strlen($alphabet);
  52. $bits = (int) ceil(log($alphabetSize, 2.0));
  53. if ($bits <= 0 || $bits > 56) {
  54. throw new InvalidArgumentException('The length of the alphabet must in the [2^1, 2^56] range.');
  55. }
  56. $ret = '';
  57. while ($length > 0) {
  58. $urandomLength = (int) ceil(2 * $length * $bits / 8.0);
  59. $data = random_bytes($urandomLength);
  60. $unpackedData = 0;
  61. $unpackedBits = 0;
  62. for ($i = 0; $i < $urandomLength && $length > 0; ++$i) {
  63. // Unpack 8 bits
  64. $unpackedData = ($unpackedData << 8) | \ord($data[$i]);
  65. $unpackedBits += 8;
  66. // While we have enough bits to select a character from the alphabet, keep
  67. // consuming the random data
  68. for (; $unpackedBits >= $bits && $length > 0; $unpackedBits -= $bits) {
  69. $index = ($unpackedData & ((1 << $bits) - 1));
  70. $unpackedData >>= $bits;
  71. // Unfortunately, the alphabet size is not necessarily a power of two.
  72. // Worst case, it is 2^k + 1, which means we need (k+1) bits and we
  73. // have around a 50% chance of missing as k gets larger
  74. if ($index < $alphabetSize) {
  75. $ret .= $alphabet[$index];
  76. --$length;
  77. }
  78. }
  79. }
  80. }
  81. return new static($ret);
  82. }
  83. /**
  84. * @param int $offset
  85. */
  86. public function bytesAt($offset)
  87. {
  88. $str = $this->string[$offset] ?? '';
  89. return '' === $str ? [] : [\ord($str)];
  90. }
  91. /**
  92. * @return $this
  93. * @param string ...$suffix
  94. */
  95. public function append(...$suffix)
  96. {
  97. $str = clone $this;
  98. $str->string .= 1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix);
  99. return $str;
  100. }
  101. /**
  102. * @return $this
  103. */
  104. public function camel()
  105. {
  106. $str = clone $this;
  107. $parts = explode(' ', trim(ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $this->string))));
  108. $parts[0] = 1 !== \strlen($parts[0]) && ctype_upper($parts[0]) ? $parts[0] : lcfirst($parts[0]);
  109. $str->string = implode('', $parts);
  110. return $str;
  111. }
  112. /**
  113. * @param int $length
  114. */
  115. public function chunk($length = 1)
  116. {
  117. if (1 > $length) {
  118. throw new InvalidArgumentException('The chunk length must be greater than zero.');
  119. }
  120. if ('' === $this->string) {
  121. return [];
  122. }
  123. $str = clone $this;
  124. $chunks = [];
  125. foreach (str_split($this->string, $length) as $chunk) {
  126. $str->string = $chunk;
  127. $chunks[] = clone $str;
  128. }
  129. return $chunks;
  130. }
  131. /**
  132. * @param string|mixed[]|\Symfony\Component\String\AbstractString $suffix
  133. */
  134. public function endsWith($suffix)
  135. {
  136. if ($suffix instanceof AbstractString) {
  137. $suffix = $suffix->string;
  138. } elseif (!\is_string($suffix)) {
  139. return parent::endsWith($suffix);
  140. }
  141. return '' !== $suffix && \strlen($this->string) >= \strlen($suffix) && 0 === substr_compare($this->string, $suffix, -\strlen($suffix), null, $this->ignoreCase);
  142. }
  143. /**
  144. * @param string|mixed[]|\Symfony\Component\String\AbstractString $string
  145. */
  146. public function equalsTo($string)
  147. {
  148. if ($string instanceof AbstractString) {
  149. $string = $string->string;
  150. } elseif (!\is_string($string)) {
  151. return parent::equalsTo($string);
  152. }
  153. if ('' !== $string && $this->ignoreCase) {
  154. return 0 === strcasecmp($string, $this->string);
  155. }
  156. return $string === $this->string;
  157. }
  158. /**
  159. * @return $this
  160. */
  161. public function folded()
  162. {
  163. $str = clone $this;
  164. $str->string = strtolower($str->string);
  165. return $str;
  166. }
  167. /**
  168. * @param string|mixed[]|\Symfony\Component\String\AbstractString $needle
  169. * @param int $offset
  170. */
  171. public function indexOf($needle, $offset = 0)
  172. {
  173. if ($needle instanceof AbstractString) {
  174. $needle = $needle->string;
  175. } elseif (!\is_string($needle)) {
  176. return parent::indexOf($needle, $offset);
  177. }
  178. if ('' === $needle) {
  179. return null;
  180. }
  181. $i = $this->ignoreCase ? stripos($this->string, $needle, $offset) : strpos($this->string, $needle, $offset);
  182. return false === $i ? null : $i;
  183. }
  184. /**
  185. * @param string|mixed[]|\Symfony\Component\String\AbstractString $needle
  186. * @param int $offset
  187. */
  188. public function indexOfLast($needle, $offset = 0)
  189. {
  190. if ($needle instanceof AbstractString) {
  191. $needle = $needle->string;
  192. } elseif (!\is_string($needle)) {
  193. return parent::indexOfLast($needle, $offset);
  194. }
  195. if ('' === $needle) {
  196. return null;
  197. }
  198. $i = $this->ignoreCase ? strripos($this->string, $needle, $offset) : strrpos($this->string, $needle, $offset);
  199. return false === $i ? null : $i;
  200. }
  201. public function isUtf8()
  202. {
  203. return '' === $this->string || preg_match('//u', $this->string);
  204. }
  205. /**
  206. * @return $this
  207. * @param mixed[] $strings
  208. * @param string|null $lastGlue
  209. */
  210. public function join($strings, $lastGlue = null)
  211. {
  212. $str = clone $this;
  213. $tail = null !== $lastGlue && 1 < \count($strings) ? $lastGlue.array_pop($strings) : '';
  214. $str->string = implode($this->string, $strings).$tail;
  215. return $str;
  216. }
  217. public function length()
  218. {
  219. return \strlen($this->string);
  220. }
  221. /**
  222. * @return $this
  223. */
  224. public function lower()
  225. {
  226. $str = clone $this;
  227. $str->string = strtolower($str->string);
  228. return $str;
  229. }
  230. /**
  231. * @param string $regexp
  232. * @param int $flags
  233. * @param int $offset
  234. */
  235. public function match($regexp, $flags = 0, $offset = 0)
  236. {
  237. $match = ((\PREG_PATTERN_ORDER | \PREG_SET_ORDER) & $flags) ? 'preg_match_all' : 'preg_match';
  238. if ($this->ignoreCase) {
  239. $regexp .= 'i';
  240. }
  241. set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
  242. try {
  243. if (false === $match($regexp, $this->string, $matches, $flags, $offset)) {
  244. throw new RuntimeException('Matching failed with error: '.preg_last_error_msg());
  245. }
  246. array_walk_recursive($matches, function (&$value) {
  247. if ($value === '') {
  248. $value = null;
  249. }
  250. });
  251. } finally {
  252. restore_error_handler();
  253. }
  254. return $matches;
  255. }
  256. /**
  257. * @return $this
  258. * @param int $length
  259. * @param string $padStr
  260. */
  261. public function padBoth($length, $padStr = ' ')
  262. {
  263. $str = clone $this;
  264. $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_BOTH);
  265. return $str;
  266. }
  267. /**
  268. * @return $this
  269. * @param int $length
  270. * @param string $padStr
  271. */
  272. public function padEnd($length, $padStr = ' ')
  273. {
  274. $str = clone $this;
  275. $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_RIGHT);
  276. return $str;
  277. }
  278. /**
  279. * @return $this
  280. * @param int $length
  281. * @param string $padStr
  282. */
  283. public function padStart($length, $padStr = ' ')
  284. {
  285. $str = clone $this;
  286. $str->string = str_pad($this->string, $length, $padStr, \STR_PAD_LEFT);
  287. return $str;
  288. }
  289. /**
  290. * @return $this
  291. * @param string ...$prefix
  292. */
  293. public function prepend(...$prefix)
  294. {
  295. $str = clone $this;
  296. $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$str->string;
  297. return $str;
  298. }
  299. /**
  300. * @return $this
  301. * @param string $from
  302. * @param string $to
  303. */
  304. public function replace($from, $to)
  305. {
  306. $str = clone $this;
  307. if ('' !== $from) {
  308. $str->string = $this->ignoreCase ? str_ireplace($from, $to, $this->string) : str_replace($from, $to, $this->string);
  309. }
  310. return $str;
  311. }
  312. /**
  313. * @param string|callable $to
  314. * @return $this
  315. * @param string $fromRegexp
  316. */
  317. public function replaceMatches($fromRegexp, $to)
  318. {
  319. if ($this->ignoreCase) {
  320. $fromRegexp .= 'i';
  321. }
  322. $replace = \is_array($to) || $to instanceof \Closure ? 'preg_replace_callback' : 'preg_replace';
  323. set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
  324. try {
  325. if (null === $string = $replace($fromRegexp, $to, $this->string)) {
  326. $lastError = preg_last_error();
  327. foreach (get_defined_constants(true)['pcre'] as $k => $v) {
  328. if ($lastError === $v && substr_compare($k, '_ERROR', -strlen('_ERROR')) === 0) {
  329. throw new RuntimeException('Matching failed with '.$k.'.');
  330. }
  331. }
  332. throw new RuntimeException('Matching failed with unknown error code.');
  333. }
  334. } finally {
  335. restore_error_handler();
  336. }
  337. $str = clone $this;
  338. $str->string = $string;
  339. return $str;
  340. }
  341. /**
  342. * @return $this
  343. */
  344. public function reverse()
  345. {
  346. $str = clone $this;
  347. $str->string = strrev($str->string);
  348. return $str;
  349. }
  350. /**
  351. * @return $this
  352. * @param int $start
  353. * @param int|null $length
  354. */
  355. public function slice($start = 0, $length = null)
  356. {
  357. $str = clone $this;
  358. $str->string = (string) substr($this->string, $start, $length ?? \PHP_INT_MAX);
  359. return $str;
  360. }
  361. /**
  362. * @return $this
  363. */
  364. public function snake()
  365. {
  366. $str = $this->camel();
  367. $str->string = strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $str->string));
  368. return $str;
  369. }
  370. /**
  371. * @return $this
  372. * @param string $replacement
  373. * @param int $start
  374. * @param int|null $length
  375. */
  376. public function splice($replacement, $start = 0, $length = null)
  377. {
  378. $str = clone $this;
  379. $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX);
  380. return $str;
  381. }
  382. /**
  383. * @param string $delimiter
  384. * @param int|null $limit
  385. * @param int|null $flags
  386. */
  387. public function split($delimiter, $limit = null, $flags = null)
  388. {
  389. if (1 > ($limit = $limit ?? \PHP_INT_MAX)) {
  390. throw new InvalidArgumentException('Split limit must be a positive integer.');
  391. }
  392. if ('' === $delimiter) {
  393. throw new InvalidArgumentException('Split delimiter is empty.');
  394. }
  395. if (null !== $flags) {
  396. return parent::split($delimiter, $limit, $flags);
  397. }
  398. $str = clone $this;
  399. $chunks = $this->ignoreCase
  400. ? preg_split('{'.preg_quote($delimiter).'}iD', $this->string, $limit)
  401. : explode($delimiter, $this->string, $limit);
  402. foreach ($chunks as &$chunk) {
  403. $str->string = $chunk;
  404. $chunk = clone $str;
  405. }
  406. return $chunks;
  407. }
  408. /**
  409. * @param string|mixed[]|\Symfony\Component\String\AbstractString $prefix
  410. */
  411. public function startsWith($prefix)
  412. {
  413. if ($prefix instanceof AbstractString) {
  414. $prefix = $prefix->string;
  415. } elseif (!\is_string($prefix)) {
  416. return parent::startsWith($prefix);
  417. }
  418. return '' !== $prefix && 0 === ($this->ignoreCase ? strncasecmp($this->string, $prefix, \strlen($prefix)) : strncmp($this->string, $prefix, \strlen($prefix)));
  419. }
  420. /**
  421. * @return $this
  422. * @param bool $allWords
  423. */
  424. public function title($allWords = false)
  425. {
  426. $str = clone $this;
  427. $str->string = $allWords ? ucwords($str->string) : ucfirst($str->string);
  428. return $str;
  429. }
  430. /**
  431. * @param string|null $fromEncoding
  432. */
  433. public function toUnicodeString($fromEncoding = null)
  434. {
  435. return new UnicodeString($this->toCodePointString($fromEncoding)->string);
  436. }
  437. /**
  438. * @param string|null $fromEncoding
  439. */
  440. public function toCodePointString($fromEncoding = null)
  441. {
  442. $u = new CodePointString();
  443. if (\in_array($fromEncoding, [null, 'utf8', 'utf-8', 'UTF8', 'UTF-8'], true) && preg_match('//u', $this->string)) {
  444. $u->string = $this->string;
  445. return $u;
  446. }
  447. set_error_handler(static function ($t, $m) { throw new InvalidArgumentException($m); });
  448. try {
  449. try {
  450. $validEncoding = false !== mb_detect_encoding($this->string, $fromEncoding ?? 'Windows-1252', true);
  451. } catch (InvalidArgumentException $e) {
  452. if (!\function_exists('iconv')) {
  453. throw $e;
  454. }
  455. $u->string = iconv($fromEncoding ?? 'Windows-1252', 'UTF-8', $this->string);
  456. return $u;
  457. }
  458. } finally {
  459. restore_error_handler();
  460. }
  461. if (!$validEncoding) {
  462. throw new InvalidArgumentException(sprintf('Invalid "%s" string.', $fromEncoding ?? 'Windows-1252'));
  463. }
  464. $u->string = mb_convert_encoding($this->string, 'UTF-8', $fromEncoding ?? 'Windows-1252');
  465. return $u;
  466. }
  467. /**
  468. * @return $this
  469. * @param string $chars
  470. */
  471. public function trim($chars = " \t\n\r\0\x0B\x0C")
  472. {
  473. $str = clone $this;
  474. $str->string = trim($str->string, $chars);
  475. return $str;
  476. }
  477. /**
  478. * @return $this
  479. * @param string $chars
  480. */
  481. public function trimEnd($chars = " \t\n\r\0\x0B\x0C")
  482. {
  483. $str = clone $this;
  484. $str->string = rtrim($str->string, $chars);
  485. return $str;
  486. }
  487. /**
  488. * @return $this
  489. * @param string $chars
  490. */
  491. public function trimStart($chars = " \t\n\r\0\x0B\x0C")
  492. {
  493. $str = clone $this;
  494. $str->string = ltrim($str->string, $chars);
  495. return $str;
  496. }
  497. /**
  498. * @return $this
  499. */
  500. public function upper()
  501. {
  502. $str = clone $this;
  503. $str->string = strtoupper($str->string);
  504. return $str;
  505. }
  506. /**
  507. * @param bool $ignoreAnsiDecoration
  508. */
  509. public function width($ignoreAnsiDecoration = true)
  510. {
  511. $string = preg_match('//u', $this->string) ? $this->string : preg_replace('/[\x80-\xFF]/', '?', $this->string);
  512. return (new CodePointString($string))->width($ignoreAnsiDecoration);
  513. }
  514. }