AbstractString.php 20 KB

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