Str.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154
  1. <?php
  2. namespace Illuminate\Support;
  3. use Closure;
  4. use Illuminate\Support\Traits\Macroable;
  5. use League\CommonMark\Environment\Environment;
  6. use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
  7. use League\CommonMark\Extension\InlinesOnly\InlinesOnlyExtension;
  8. use League\CommonMark\GithubFlavoredMarkdownConverter;
  9. use League\CommonMark\MarkdownConverter;
  10. use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
  11. use Ramsey\Uuid\Exception\InvalidUuidStringException;
  12. use Ramsey\Uuid\Generator\CombGenerator;
  13. use Ramsey\Uuid\Rfc4122\FieldsInterface;
  14. use Ramsey\Uuid\Uuid;
  15. use Ramsey\Uuid\UuidFactory;
  16. use Symfony\Component\Uid\Ulid;
  17. use Throwable;
  18. use Traversable;
  19. use voku\helper\ASCII;
  20. class Str
  21. {
  22. use Macroable;
  23. /**
  24. * The list of characters that are considered "invisible" in strings.
  25. *
  26. * @var string
  27. */
  28. const INVISIBLE_CHARACTERS = '\x{0009}\x{0020}\x{00A0}\x{00AD}\x{034F}\x{061C}\x{115F}\x{1160}\x{17B4}\x{17B5}\x{180E}\x{2000}\x{2001}\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}\x{200A}\x{200B}\x{200C}\x{200D}\x{200E}\x{200F}\x{202F}\x{205F}\x{2060}\x{2061}\x{2062}\x{2063}\x{2064}\x{2065}\x{206A}\x{206B}\x{206C}\x{206D}\x{206E}\x{206F}\x{3000}\x{2800}\x{3164}\x{FEFF}\x{FFA0}\x{1D159}\x{1D173}\x{1D174}\x{1D175}\x{1D176}\x{1D177}\x{1D178}\x{1D179}\x{1D17A}\x{E0020}';
  29. /**
  30. * The cache of snake-cased words.
  31. *
  32. * @var array<string, string>
  33. */
  34. protected static $snakeCache = [];
  35. /**
  36. * The cache of camel-cased words.
  37. *
  38. * @var array<string, string>
  39. */
  40. protected static $camelCache = [];
  41. /**
  42. * The cache of studly-cased words.
  43. *
  44. * @var array<string, string>
  45. */
  46. protected static $studlyCache = [];
  47. /**
  48. * The callback that should be used to generate UUIDs.
  49. *
  50. * @var (callable(): \Ramsey\Uuid\UuidInterface)|null
  51. */
  52. protected static $uuidFactory;
  53. /**
  54. * The callback that should be used to generate ULIDs.
  55. *
  56. * @var (callable(): \Symfony\Component\Uid\Ulid)|null
  57. */
  58. protected static $ulidFactory;
  59. /**
  60. * The callback that should be used to generate random strings.
  61. *
  62. * @var (callable(int): string)|null
  63. */
  64. protected static $randomStringFactory;
  65. /**
  66. * Get a new stringable object from the given string.
  67. *
  68. * @param string $string
  69. * @return \Illuminate\Support\Stringable
  70. */
  71. public static function of($string)
  72. {
  73. return new Stringable($string);
  74. }
  75. /**
  76. * Return the remainder of a string after the first occurrence of a given value.
  77. *
  78. * @param string $subject
  79. * @param string $search
  80. * @return string
  81. */
  82. public static function after($subject, $search)
  83. {
  84. return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
  85. }
  86. /**
  87. * Return the remainder of a string after the last occurrence of a given value.
  88. *
  89. * @param string $subject
  90. * @param string $search
  91. * @return string
  92. */
  93. public static function afterLast($subject, $search)
  94. {
  95. if ($search === '') {
  96. return $subject;
  97. }
  98. $position = mb_strrpos($subject, $search);
  99. if ($position === false) {
  100. return $subject;
  101. }
  102. return static::substr($subject, $position + static::length($search));
  103. }
  104. /**
  105. * Transliterate a UTF-8 value to ASCII.
  106. *
  107. * @param string $value
  108. * @param string $language
  109. * @return string
  110. */
  111. public static function ascii($value, $language = 'en')
  112. {
  113. return ASCII::to_ascii((string) $value, $language, replace_single_chars_only: false);
  114. }
  115. /**
  116. * Transliterate a string to its closest ASCII representation.
  117. *
  118. * @param string $string
  119. * @param string|null $unknown
  120. * @param bool|null $strict
  121. * @return string
  122. */
  123. public static function transliterate($string, $unknown = '?', $strict = false)
  124. {
  125. return ASCII::to_transliterate($string, $unknown, $strict);
  126. }
  127. /**
  128. * Get the portion of a string before the first occurrence of a given value.
  129. *
  130. * @param string $subject
  131. * @param string $search
  132. * @return string
  133. */
  134. public static function before($subject, $search)
  135. {
  136. if ($search === '') {
  137. return $subject;
  138. }
  139. $result = strstr($subject, (string) $search, true);
  140. return $result === false ? $subject : $result;
  141. }
  142. /**
  143. * Get the portion of a string before the last occurrence of a given value.
  144. *
  145. * @param string $subject
  146. * @param string $search
  147. * @return string
  148. */
  149. public static function beforeLast($subject, $search)
  150. {
  151. if ($search === '') {
  152. return $subject;
  153. }
  154. $pos = mb_strrpos($subject, $search);
  155. if ($pos === false) {
  156. return $subject;
  157. }
  158. return static::substr($subject, 0, $pos);
  159. }
  160. /**
  161. * Get the portion of a string between two given values.
  162. *
  163. * @param string $subject
  164. * @param string $from
  165. * @param string $to
  166. * @return string
  167. */
  168. public static function between($subject, $from, $to)
  169. {
  170. if ($from === '' || $to === '') {
  171. return $subject;
  172. }
  173. return static::beforeLast(static::after($subject, $from), $to);
  174. }
  175. /**
  176. * Get the smallest possible portion of a string between two given values.
  177. *
  178. * @param string $subject
  179. * @param string $from
  180. * @param string $to
  181. * @return string
  182. */
  183. public static function betweenFirst($subject, $from, $to)
  184. {
  185. if ($from === '' || $to === '') {
  186. return $subject;
  187. }
  188. return static::before(static::after($subject, $from), $to);
  189. }
  190. /**
  191. * Convert a value to camel case.
  192. *
  193. * @param string $value
  194. * @return ($value is '' ? '' : string)
  195. */
  196. public static function camel($value)
  197. {
  198. if (isset(static::$camelCache[$value])) {
  199. return static::$camelCache[$value];
  200. }
  201. return static::$camelCache[$value] = lcfirst(static::studly($value));
  202. }
  203. /**
  204. * Get the character at the specified index.
  205. *
  206. * @param string $subject
  207. * @param int $index
  208. * @return string|false
  209. */
  210. public static function charAt($subject, $index)
  211. {
  212. $length = mb_strlen($subject);
  213. if ($index < 0 ? $index < -$length : $index > $length - 1) {
  214. return false;
  215. }
  216. return mb_substr($subject, $index, 1);
  217. }
  218. /**
  219. * Remove the given string(s) if it exists at the start of the haystack.
  220. *
  221. * @param string $subject
  222. * @param string|string[] $needle
  223. * @return string
  224. */
  225. public static function chopStart($subject, $needle)
  226. {
  227. foreach ((array) $needle as $n) {
  228. if ($n !== '' && str_starts_with($subject, $n)) {
  229. return mb_substr($subject, mb_strlen($n));
  230. }
  231. }
  232. return $subject;
  233. }
  234. /**
  235. * Remove the given string(s) if it exists at the end of the haystack.
  236. *
  237. * @param string $subject
  238. * @param string|string[] $needle
  239. * @return string
  240. */
  241. public static function chopEnd($subject, $needle)
  242. {
  243. foreach ((array) $needle as $n) {
  244. if ($n !== '' && str_ends_with($subject, $n)) {
  245. return mb_substr($subject, 0, -mb_strlen($n));
  246. }
  247. }
  248. return $subject;
  249. }
  250. /**
  251. * Determine if a given string contains a given substring.
  252. *
  253. * @param string $haystack
  254. * @param string|iterable<string> $needles
  255. * @param bool $ignoreCase
  256. * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
  257. */
  258. public static function contains($haystack, $needles, $ignoreCase = false)
  259. {
  260. if (is_null($haystack)) {
  261. return false;
  262. }
  263. if ($ignoreCase) {
  264. $haystack = mb_strtolower($haystack);
  265. }
  266. if (! is_iterable($needles)) {
  267. $needles = (array) $needles;
  268. }
  269. foreach ($needles as $needle) {
  270. if ($ignoreCase) {
  271. $needle = mb_strtolower($needle);
  272. }
  273. if ($needle !== '' && str_contains($haystack, $needle)) {
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. /**
  280. * Determine if a given string contains all array values.
  281. *
  282. * @param string $haystack
  283. * @param iterable<string> $needles
  284. * @param bool $ignoreCase
  285. * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
  286. */
  287. public static function containsAll($haystack, $needles, $ignoreCase = false)
  288. {
  289. foreach ($needles as $needle) {
  290. if (! static::contains($haystack, $needle, $ignoreCase)) {
  291. return false;
  292. }
  293. }
  294. return true;
  295. }
  296. /**
  297. * Determine if a given string doesn't contain a given substring.
  298. *
  299. * @param string $haystack
  300. * @param string|iterable<string> $needles
  301. * @param bool $ignoreCase
  302. * @return ($needles is array{} ? true : ($haystack is non-empty-string ? bool : true))
  303. */
  304. public static function doesntContain($haystack, $needles, $ignoreCase = false)
  305. {
  306. return ! static::contains($haystack, $needles, $ignoreCase);
  307. }
  308. /**
  309. * Convert the case of a string.
  310. *
  311. * @param string $string
  312. * @param MB_CASE_UPPER|MB_CASE_LOWER|MB_CASE_TITLE|MB_CASE_FOLD|MB_CASE_UPPER_SIMPLE|MB_CASE_LOWER_SIMPLE|MB_CASE_TITLE_SIMPLE|MB_CASE_FOLD_SIMPLE $mode
  313. * @param string|null $encoding
  314. * @return ($string is '' ? '' : string)
  315. */
  316. public static function convertCase(string $string, int $mode = MB_CASE_FOLD, ?string $encoding = 'UTF-8')
  317. {
  318. return mb_convert_case($string, $mode, $encoding);
  319. }
  320. /**
  321. * Replace consecutive instances of a given character with a single character in the given string.
  322. *
  323. * @param string $string
  324. * @param array<string>|string $characters
  325. * @return ($string is '' ? '' : string)
  326. */
  327. public static function deduplicate(string $string, array|string $characters = ' ')
  328. {
  329. if (is_string($characters)) {
  330. return preg_replace('/'.preg_quote($characters, '/').'+/u', $characters, $string);
  331. }
  332. return array_reduce(
  333. $characters,
  334. fn ($carry, $character) => preg_replace('/'.preg_quote($character, '/').'+/u', $character, $carry),
  335. $string
  336. );
  337. }
  338. /**
  339. * Determine if a given string ends with a given substring.
  340. *
  341. * @param string $haystack
  342. * @param string|iterable<string> $needles
  343. * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
  344. */
  345. public static function endsWith($haystack, $needles)
  346. {
  347. if (is_null($haystack)) {
  348. return false;
  349. }
  350. if (! is_iterable($needles)) {
  351. $needles = (array) $needles;
  352. }
  353. foreach ($needles as $needle) {
  354. if ((string) $needle !== '' && str_ends_with($haystack, $needle)) {
  355. return true;
  356. }
  357. }
  358. return false;
  359. }
  360. /**
  361. * Determine if a given string doesn't end with a given substring.
  362. *
  363. * @param string $haystack
  364. * @param string|iterable<string> $needles
  365. * @return ($needles is array{} ? true : ($haystack is non-empty-string ? bool : true))
  366. */
  367. public static function doesntEndWith($haystack, $needles)
  368. {
  369. return ! static::endsWith($haystack, $needles);
  370. }
  371. /**
  372. * Extracts an excerpt from text that matches the first instance of a phrase.
  373. *
  374. * @param string $text
  375. * @param string $phrase
  376. * @param array{radius?: int|float, omission?: string} $options
  377. * @return string|null
  378. */
  379. public static function excerpt($text, $phrase = '', $options = [])
  380. {
  381. $radius = $options['radius'] ?? 100;
  382. $omission = $options['omission'] ?? '...';
  383. preg_match('/^(.*?)('.preg_quote((string) $phrase, '/').')(.*)$/iu', (string) $text, $matches);
  384. if (empty($matches)) {
  385. return null;
  386. }
  387. $start = ltrim($matches[1]);
  388. $start = Str::of(mb_substr($start, max(mb_strlen($start, 'UTF-8') - $radius, 0), $radius, 'UTF-8'))->ltrim()->unless(
  389. fn ($startWithRadius) => $startWithRadius->exactly($start),
  390. fn ($startWithRadius) => $startWithRadius->prepend($omission),
  391. );
  392. $end = rtrim($matches[3]);
  393. $end = Str::of(mb_substr($end, 0, $radius, 'UTF-8'))->rtrim()->unless(
  394. fn ($endWithRadius) => $endWithRadius->exactly($end),
  395. fn ($endWithRadius) => $endWithRadius->append($omission),
  396. );
  397. return $start->append($matches[2], $end)->toString();
  398. }
  399. /**
  400. * Cap a string with a single instance of a given value.
  401. *
  402. * @param string $value
  403. * @param string $cap
  404. * @return ($value is '' ? ($cap is '' ? '' : non-empty-string) : non-empty-string)
  405. */
  406. public static function finish($value, $cap)
  407. {
  408. $quoted = preg_quote($cap, '/');
  409. return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
  410. }
  411. /**
  412. * Wrap the string with the given strings.
  413. *
  414. * @param string $value
  415. * @param string $before
  416. * @param string|null $after
  417. * @return ($value is '' ? ($before is '' ? ($after is '' ? '' : ($after is null ? '' : non-empty-string)) : non-empty-string) : non-empty-string)
  418. */
  419. public static function wrap($value, $before, $after = null)
  420. {
  421. return $before.$value.($after ?? $before);
  422. }
  423. /**
  424. * Unwrap the string with the given strings.
  425. *
  426. * @param string $value
  427. * @param string $before
  428. * @param string|null $after
  429. * @return string
  430. */
  431. public static function unwrap($value, $before, $after = null)
  432. {
  433. if (static::startsWith($value, $before)) {
  434. $value = static::substr($value, static::length($before));
  435. }
  436. if (static::endsWith($value, $after ??= $before)) {
  437. $value = static::substr($value, 0, -static::length($after));
  438. }
  439. return $value;
  440. }
  441. /**
  442. * Determine if a given string matches a given pattern.
  443. *
  444. * @param string|iterable<string> $pattern
  445. * @param string $value
  446. * @param bool $ignoreCase
  447. * @return bool
  448. */
  449. public static function is($pattern, $value, $ignoreCase = false)
  450. {
  451. $value = (string) $value;
  452. if (! is_iterable($pattern)) {
  453. $pattern = [$pattern];
  454. }
  455. foreach ($pattern as $pattern) {
  456. $pattern = (string) $pattern;
  457. // If the given value is an exact match we can of course return true right
  458. // from the beginning. Otherwise, we will translate asterisks and do an
  459. // actual pattern match against the two strings to see if they match.
  460. if ($pattern === '*' || $pattern === $value) {
  461. return true;
  462. }
  463. if ($ignoreCase && mb_strtolower($pattern) === mb_strtolower($value)) {
  464. return true;
  465. }
  466. $pattern = preg_quote($pattern, '#');
  467. // Asterisks are translated into zero-or-more regular expression wildcards
  468. // to make it convenient to check if the strings starts with the given
  469. // pattern such as "library/*", making any string check convenient.
  470. $pattern = str_replace('\*', '.*', $pattern);
  471. if (preg_match('#^'.$pattern.'\z#'.($ignoreCase ? 'isu' : 'su'), $value) === 1) {
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. /**
  478. * Determine if a given string is 7 bit ASCII.
  479. *
  480. * @param string $value
  481. * @return bool
  482. */
  483. public static function isAscii($value)
  484. {
  485. return ASCII::is_ascii((string) $value);
  486. }
  487. /**
  488. * Determine if a given value is valid JSON.
  489. *
  490. * @param mixed $value
  491. * @return bool
  492. *
  493. * @phpstan-assert-if-true =non-empty-string $value
  494. */
  495. public static function isJson($value)
  496. {
  497. if (! is_string($value)) {
  498. return false;
  499. }
  500. return json_validate($value, 512);
  501. }
  502. /**
  503. * Determine if a given value is a valid URL.
  504. *
  505. * @param mixed $value
  506. * @param string[] $protocols
  507. * @return bool
  508. *
  509. * @phpstan-assert-if-true =non-empty-string $value
  510. */
  511. public static function isUrl($value, array $protocols = [])
  512. {
  513. if (! is_string($value)) {
  514. return false;
  515. }
  516. $protocolList = empty($protocols)
  517. ? 'aaa|aaas|about|acap|acct|acd|acr|adiumxtra|adt|afp|afs|aim|amss|android|appdata|apt|ark|attachment|aw|barion|beshare|bitcoin|bitcoincash|blob|bolo|browserext|calculator|callto|cap|cast|casts|chrome|chrome-extension|cid|coap|coap\+tcp|coap\+ws|coaps|coaps\+tcp|coaps\+ws|com-eventbrite-attendee|content|conti|crid|cvs|dab|data|dav|diaspora|dict|did|dis|dlna-playcontainer|dlna-playsingle|dns|dntp|dpp|drm|drop|dtn|dvb|ed2k|elsi|example|facetime|fax|feed|feedready|file|filesystem|finger|first-run-pen-experience|fish|fm|ftp|fuchsia-pkg|geo|gg|git|gizmoproject|go|gopher|graph|gtalk|h323|ham|hcap|hcp|http|https|hxxp|hxxps|hydrazone|iax|icap|icon|im|imap|info|iotdisco|ipn|ipp|ipps|irc|irc6|ircs|iris|iris\.beep|iris\.lwz|iris\.xpc|iris\.xpcs|isostore|itms|jabber|jar|jms|keyparc|lastfm|ldap|ldaps|leaptofrogans|lorawan|lvlt|magnet|mailserver|mailto|maps|market|message|mid|mms|modem|mongodb|moz|ms-access|ms-browser-extension|ms-calculator|ms-drive-to|ms-enrollment|ms-excel|ms-eyecontrolspeech|ms-gamebarservices|ms-gamingoverlay|ms-getoffice|ms-help|ms-infopath|ms-inputapp|ms-lockscreencomponent-config|ms-media-stream-id|ms-mixedrealitycapture|ms-mobileplans|ms-officeapp|ms-people|ms-project|ms-powerpoint|ms-publisher|ms-restoretabcompanion|ms-screenclip|ms-screensketch|ms-search|ms-search-repair|ms-secondary-screen-controller|ms-secondary-screen-setup|ms-settings|ms-settings-airplanemode|ms-settings-bluetooth|ms-settings-camera|ms-settings-cellular|ms-settings-cloudstorage|ms-settings-connectabledevices|ms-settings-displays-topology|ms-settings-emailandaccounts|ms-settings-language|ms-settings-location|ms-settings-lock|ms-settings-nfctransactions|ms-settings-notifications|ms-settings-power|ms-settings-privacy|ms-settings-proximity|ms-settings-screenrotation|ms-settings-wifi|ms-settings-workplace|ms-spd|ms-sttoverlay|ms-transit-to|ms-useractivityset|ms-virtualtouchpad|ms-visio|ms-walk-to|ms-whiteboard|ms-whiteboard-cmd|ms-word|msnim|msrp|msrps|mss|mtqp|mumble|mupdate|mvn|news|nfs|ni|nih|nntp|notes|ocf|oid|onenote|onenote-cmd|opaquelocktoken|openpgp4fpr|pack|palm|paparazzi|payto|pkcs11|platform|pop|pres|prospero|proxy|pwid|psyc|pttp|qb|query|redis|rediss|reload|res|resource|rmi|rsync|rtmfp|rtmp|rtsp|rtsps|rtspu|s3|secondlife|service|session|sftp|sgn|shttp|sieve|simpleledger|sip|sips|skype|smb|sms|smtp|snews|snmp|soap\.beep|soap\.beeps|soldat|spiffe|spotify|ssh|steam|stun|stuns|submit|svn|tag|teamspeak|tel|teliaeid|telnet|tftp|tg|things|thismessage|tip|tn3270|tool|ts3server|turn|turns|tv|udp|unreal|urn|ut2004|v-event|vemmi|ventrilo|videotex|vnc|view-source|wais|webcal|wpid|ws|wss|wtai|wyciwyg|xcon|xcon-userid|xfire|xmlrpc\.beep|xmlrpc\.beeps|xmpp|xri|ymsgr|z39\.50|z39\.50r|z39\.50s'
  518. : implode('|', $protocols);
  519. /*
  520. * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (5.0.7).
  521. *
  522. * (c) Fabien Potencier <fabien@symfony.com> http://symfony.com
  523. */
  524. $pattern = '~^
  525. (LARAVEL_PROTOCOLS):// # protocol
  526. (((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%[0-9A-Fa-f]{2})+)@)? # basic auth
  527. (
  528. (?:
  529. (?:
  530. (?:[\pL\pN\pS\pM\-\_]++\.)+
  531. (?:
  532. (?:xn--[a-z0-9-]++) # punycode in tld
  533. |
  534. (?:[\pL\pN\pM]++) # no punycode in tld
  535. )
  536. ) # a multi-level domain name
  537. |
  538. [a-z0-9\-\_]++ # a single-level domain name
  539. )\.?
  540. | # or
  541. \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address
  542. | # or
  543. \[
  544. (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::))))
  545. \] # an IPv6 address
  546. )
  547. (:[0-9]+)? # a port (optional)
  548. (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})* )* # a path
  549. (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a query (optional)
  550. (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # a fragment (optional)
  551. $~ixu';
  552. return preg_match(str_replace('LARAVEL_PROTOCOLS', $protocolList, $pattern), $value) > 0;
  553. }
  554. /**
  555. * Determine if a given value is a valid UUID.
  556. *
  557. * @param mixed $value
  558. * @param int<0, 8>|'nil'|'max'|null $version
  559. * @return bool
  560. *
  561. * @phpstan-assert-if-true =non-empty-string $value
  562. */
  563. public static function isUuid($value, $version = null)
  564. {
  565. if (! is_string($value)) {
  566. return false;
  567. }
  568. if ($version === null) {
  569. return preg_match('/^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$/D', $value) > 0;
  570. }
  571. $factory = new UuidFactory;
  572. try {
  573. $factoryUuid = $factory->fromString($value);
  574. } catch (InvalidUuidStringException) {
  575. return false;
  576. }
  577. $fields = $factoryUuid->getFields();
  578. if (! ($fields instanceof FieldsInterface)) {
  579. return false;
  580. }
  581. if ($version === 0 || $version === 'nil') {
  582. return $fields->isNil();
  583. }
  584. if ($version === 'max') {
  585. return $fields->isMax();
  586. }
  587. return $fields->getVersion() === $version;
  588. }
  589. /**
  590. * Determine if a given value is a valid ULID.
  591. *
  592. * @param mixed $value
  593. * @return bool
  594. *
  595. * @phpstan-assert-if-true =non-empty-string $value
  596. */
  597. public static function isUlid($value)
  598. {
  599. if (! is_string($value)) {
  600. return false;
  601. }
  602. return Ulid::isValid($value);
  603. }
  604. /**
  605. * Convert a string to kebab case.
  606. *
  607. * @param string $value
  608. * @return ($value is '' ? '' : string)
  609. */
  610. public static function kebab($value)
  611. {
  612. return static::snake($value, '-');
  613. }
  614. /**
  615. * Return the length of the given string.
  616. *
  617. * @param string $value
  618. * @param string|null $encoding
  619. * @return non-negative-int
  620. */
  621. public static function length($value, $encoding = null)
  622. {
  623. return mb_strlen($value, $encoding);
  624. }
  625. /**
  626. * Limit the number of characters in a string.
  627. *
  628. * @param string $value
  629. * @param int $limit
  630. * @param string $end
  631. * @param bool $preserveWords
  632. * @return string
  633. */
  634. public static function limit($value, $limit = 100, $end = '...', $preserveWords = false)
  635. {
  636. if (mb_strwidth($value, 'UTF-8') <= $limit) {
  637. return $value;
  638. }
  639. if (! $preserveWords) {
  640. return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
  641. }
  642. $value = trim(preg_replace('/[\n\r]+/', ' ', strip_tags($value)));
  643. $trimmed = rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8'));
  644. if (mb_substr($value, $limit, 1, 'UTF-8') === ' ') {
  645. return $trimmed.$end;
  646. }
  647. return preg_replace("/(.*)\s.*/", '$1', $trimmed).$end;
  648. }
  649. /**
  650. * Convert the given string to lower-case.
  651. *
  652. * @param string $value
  653. * @return ($value is '' ? '' : non-empty-string&lowercase-string)
  654. */
  655. public static function lower($value)
  656. {
  657. return mb_strtolower($value, 'UTF-8');
  658. }
  659. /**
  660. * Limit the number of words in a string.
  661. *
  662. * @param string $value
  663. * @param int $words
  664. * @param string $end
  665. * @return string
  666. */
  667. public static function words($value, $words = 100, $end = '...')
  668. {
  669. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  670. if (! isset($matches[0]) || static::length($value) === static::length($matches[0])) {
  671. return $value;
  672. }
  673. return rtrim($matches[0]).$end;
  674. }
  675. /**
  676. * Converts GitHub flavored Markdown into HTML.
  677. *
  678. * @param string $string
  679. * @param array $options
  680. * @param \League\CommonMark\Extension\ExtensionInterface[] $extensions
  681. * @return ($string is '' ? '' : string)
  682. */
  683. public static function markdown($string, array $options = [], array $extensions = [])
  684. {
  685. $converter = new GithubFlavoredMarkdownConverter($options);
  686. $environment = $converter->getEnvironment();
  687. foreach ($extensions as $extension) {
  688. $environment->addExtension($extension);
  689. }
  690. return (string) $converter->convert($string);
  691. }
  692. /**
  693. * Converts inline Markdown into HTML.
  694. *
  695. * @param string $string
  696. * @param array $options
  697. * @param \League\CommonMark\Extension\ExtensionInterface[] $extensions
  698. * @return ($string is '' ? '' : string)
  699. */
  700. public static function inlineMarkdown($string, array $options = [], array $extensions = [])
  701. {
  702. $environment = new Environment($options);
  703. $environment->addExtension(new GithubFlavoredMarkdownExtension());
  704. $environment->addExtension(new InlinesOnlyExtension());
  705. foreach ($extensions as $extension) {
  706. $environment->addExtension($extension);
  707. }
  708. $converter = new MarkdownConverter($environment);
  709. return (string) $converter->convert($string);
  710. }
  711. /**
  712. * Masks a portion of a string with a repeated character.
  713. *
  714. * @param string $string
  715. * @param string $character
  716. * @param int $index
  717. * @param int|null $length
  718. * @param string $encoding
  719. * @return string
  720. */
  721. public static function mask($string, $character, $index, $length = null, $encoding = 'UTF-8')
  722. {
  723. if ($character === '') {
  724. return $string;
  725. }
  726. $segment = mb_substr($string, $index, $length, $encoding);
  727. if ($segment === '') {
  728. return $string;
  729. }
  730. $strlen = mb_strlen($string, $encoding);
  731. $startIndex = $index;
  732. if ($index < 0) {
  733. $startIndex = $index < -$strlen ? 0 : $strlen + $index;
  734. }
  735. $start = mb_substr($string, 0, $startIndex, $encoding);
  736. $segmentLen = mb_strlen($segment, $encoding);
  737. $end = mb_substr($string, $startIndex + $segmentLen);
  738. return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end;
  739. }
  740. /**
  741. * Get the string matching the given pattern.
  742. *
  743. * @param string $pattern
  744. * @param string $subject
  745. * @return string
  746. */
  747. public static function match($pattern, $subject)
  748. {
  749. preg_match($pattern, $subject, $matches);
  750. if (! $matches) {
  751. return '';
  752. }
  753. return $matches[1] ?? $matches[0];
  754. }
  755. /**
  756. * Determine if a given string matches a given pattern.
  757. *
  758. * @param string|iterable<string> $pattern
  759. * @param string $value
  760. * @return ($pattern is array{} ? false : bool)
  761. */
  762. public static function isMatch($pattern, $value)
  763. {
  764. $value = (string) $value;
  765. if (! is_iterable($pattern)) {
  766. $pattern = [$pattern];
  767. }
  768. foreach ($pattern as $pattern) {
  769. $pattern = (string) $pattern;
  770. if (preg_match($pattern, $value) === 1) {
  771. return true;
  772. }
  773. }
  774. return false;
  775. }
  776. /**
  777. * Get the string matching the given pattern.
  778. *
  779. * @param string $pattern
  780. * @param string $subject
  781. * @return \Illuminate\Support\Collection
  782. */
  783. public static function matchAll($pattern, $subject)
  784. {
  785. preg_match_all($pattern, $subject, $matches);
  786. if (empty($matches[0])) {
  787. return new Collection;
  788. }
  789. return new Collection($matches[1] ?? $matches[0]);
  790. }
  791. /**
  792. * Remove all non-numeric characters from a string.
  793. *
  794. * @param string $value
  795. * @return string
  796. */
  797. public static function numbers($value)
  798. {
  799. return preg_replace('/[^0-9]/', '', $value);
  800. }
  801. /**
  802. * Pad both sides of a string with another.
  803. *
  804. * @param string $value
  805. * @param int $length
  806. * @param string $pad
  807. * @return string
  808. */
  809. public static function padBoth($value, $length, $pad = ' ')
  810. {
  811. return mb_str_pad($value, $length, $pad, STR_PAD_BOTH);
  812. }
  813. /**
  814. * Pad the left side of a string with another.
  815. *
  816. * @param string $value
  817. * @param int $length
  818. * @param string $pad
  819. * @return string
  820. */
  821. public static function padLeft($value, $length, $pad = ' ')
  822. {
  823. return mb_str_pad($value, $length, $pad, STR_PAD_LEFT);
  824. }
  825. /**
  826. * Pad the right side of a string with another.
  827. *
  828. * @param string $value
  829. * @param int $length
  830. * @param string $pad
  831. * @return string
  832. */
  833. public static function padRight($value, $length, $pad = ' ')
  834. {
  835. return mb_str_pad($value, $length, $pad, STR_PAD_RIGHT);
  836. }
  837. /**
  838. * Parse a Class[@]method style callback into class and method.
  839. *
  840. * @param string $callback
  841. * @param string|null $default
  842. * @return array<int, string|null>
  843. */
  844. public static function parseCallback($callback, $default = null)
  845. {
  846. if (static::contains($callback, "@anonymous\0")) {
  847. if (static::substrCount($callback, '@') > 1) {
  848. return [
  849. static::beforeLast($callback, '@'),
  850. static::afterLast($callback, '@'),
  851. ];
  852. }
  853. return [$callback, $default];
  854. }
  855. return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default];
  856. }
  857. /**
  858. * Get the plural form of an English word.
  859. *
  860. * @param string $value
  861. * @param int|array|\Countable $count
  862. * @param bool $prependCount
  863. * @return string
  864. */
  865. public static function plural($value, $count = 2, $prependCount = false)
  866. {
  867. if (is_countable($count)) {
  868. $count = count($count);
  869. }
  870. return ($prependCount ? Number::format($count).' ' : '').Pluralizer::plural($value, $count);
  871. }
  872. /**
  873. * Pluralize the last word of an English, studly caps case string.
  874. *
  875. * @param string $value
  876. * @param int|array|\Countable $count
  877. * @return string
  878. */
  879. public static function pluralStudly($value, $count = 2)
  880. {
  881. $parts = preg_split('/(.)(?=[A-Z])/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
  882. $lastWord = array_pop($parts);
  883. return implode('', $parts).self::plural($lastWord, $count);
  884. }
  885. /**
  886. * Pluralize the last word of an English, Pascal caps case string.
  887. *
  888. * @param string $value
  889. * @param int|array|\Countable $count
  890. * @return string
  891. */
  892. public static function pluralPascal($value, $count = 2)
  893. {
  894. return static::pluralStudly($value, $count);
  895. }
  896. /**
  897. * Generate a random, secure password.
  898. *
  899. * @param int $length
  900. * @param bool $letters
  901. * @param bool $numbers
  902. * @param bool $symbols
  903. * @param bool $spaces
  904. * @return ($letters is false ? ($numbers is true ? ($symbols is false ? ($spaces is false ? numeric-string : string) : string) : string) : string)
  905. */
  906. public static function password($length = 32, $letters = true, $numbers = true, $symbols = true, $spaces = false)
  907. {
  908. $password = new Collection();
  909. $options = (new Collection([
  910. 'letters' => $letters === true ? [
  911. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
  912. 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  913. 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
  914. 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  915. 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  916. ] : null,
  917. 'numbers' => $numbers === true ? [
  918. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  919. ] : null,
  920. 'symbols' => $symbols === true ? [
  921. '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',
  922. '_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[',
  923. ']', '|', ':', ';',
  924. ] : null,
  925. 'spaces' => $spaces === true ? [' '] : null,
  926. ]))
  927. ->filter()
  928. ->each(fn ($c) => $password->push($c[random_int(0, count($c) - 1)]))
  929. ->flatten();
  930. $length = $length - $password->count();
  931. return $password->merge($options->pipe(
  932. fn ($c) => Collection::times($length, fn () => $c[random_int(0, $c->count() - 1)])
  933. ))->shuffle()->implode('');
  934. }
  935. /**
  936. * Find the multi-byte safe position of the first occurrence of a given substring in a string.
  937. *
  938. * @param string $haystack
  939. * @param string $needle
  940. * @param int $offset
  941. * @param string|null $encoding
  942. * @return ($haystack is '' ? false : ($needle is '' ? false : int|false))
  943. */
  944. public static function position($haystack, $needle, $offset = 0, $encoding = null)
  945. {
  946. return mb_strpos($haystack, (string) $needle, $offset, $encoding);
  947. }
  948. /**
  949. * Generate a more truly "random" alpha-numeric string.
  950. *
  951. * @param int $length
  952. * @return string
  953. */
  954. public static function random($length = 16)
  955. {
  956. return (static::$randomStringFactory ?? function ($length) {
  957. $string = '';
  958. while (($len = strlen($string)) < $length) {
  959. $size = $length - $len;
  960. $bytesSize = (int) ceil($size / 3) * 3;
  961. $bytes = random_bytes($bytesSize);
  962. $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
  963. }
  964. return $string;
  965. })($length);
  966. }
  967. /**
  968. * Set the callable that will be used to generate random strings.
  969. *
  970. * @param (callable(int): string)|null $factory
  971. * @return void
  972. */
  973. public static function createRandomStringsUsing(?callable $factory = null)
  974. {
  975. static::$randomStringFactory = $factory;
  976. }
  977. /**
  978. * Set the sequence that will be used to generate random strings.
  979. *
  980. * @param string[] $sequence
  981. * @param (callable(int): string)|null $whenMissing
  982. * @return void
  983. */
  984. public static function createRandomStringsUsingSequence(array $sequence, $whenMissing = null)
  985. {
  986. $next = 0;
  987. $whenMissing ??= function ($length) use (&$next) {
  988. $factoryCache = static::$randomStringFactory;
  989. static::$randomStringFactory = null;
  990. $randomString = static::random($length);
  991. static::$randomStringFactory = $factoryCache;
  992. $next++;
  993. return $randomString;
  994. };
  995. static::createRandomStringsUsing(function ($length) use (&$next, $sequence, $whenMissing) {
  996. if (array_key_exists($next, $sequence)) {
  997. return $sequence[$next++];
  998. }
  999. return $whenMissing($length);
  1000. });
  1001. }
  1002. /**
  1003. * Indicate that random strings should be created normally and not using a custom factory.
  1004. *
  1005. * @return void
  1006. */
  1007. public static function createRandomStringsNormally()
  1008. {
  1009. static::$randomStringFactory = null;
  1010. }
  1011. /**
  1012. * Repeat the given string.
  1013. *
  1014. * @param string $string
  1015. * @param int $times
  1016. * @return string
  1017. */
  1018. public static function repeat(string $string, int $times)
  1019. {
  1020. return str_repeat($string, $times);
  1021. }
  1022. /**
  1023. * Replace a given value in the string sequentially with an array.
  1024. *
  1025. * @param string $search
  1026. * @param iterable<string> $replace
  1027. * @param string $subject
  1028. * @return string
  1029. */
  1030. public static function replaceArray($search, $replace, $subject)
  1031. {
  1032. if ($replace instanceof Traversable) {
  1033. $replace = Arr::from($replace);
  1034. }
  1035. $segments = explode($search, $subject);
  1036. $result = array_shift($segments);
  1037. foreach ($segments as $segment) {
  1038. $result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment;
  1039. }
  1040. return $result;
  1041. }
  1042. /**
  1043. * Convert the given value to a string or return the given fallback on failure.
  1044. *
  1045. * @param mixed $value
  1046. * @param string $fallback
  1047. * @return string
  1048. */
  1049. private static function toStringOr($value, $fallback)
  1050. {
  1051. try {
  1052. return (string) $value;
  1053. } catch (Throwable $e) {
  1054. return $fallback;
  1055. }
  1056. }
  1057. /**
  1058. * Replace the given value in the given string.
  1059. *
  1060. * @param string|iterable<string> $search
  1061. * @param string|iterable<string> $replace
  1062. * @param string|iterable<string> $subject
  1063. * @param bool $caseSensitive
  1064. * @return ($subject is string ? string : string[])
  1065. */
  1066. public static function replace($search, $replace, $subject, $caseSensitive = true)
  1067. {
  1068. if ($search instanceof Traversable) {
  1069. $search = Arr::from($search);
  1070. }
  1071. if ($replace instanceof Traversable) {
  1072. $replace = Arr::from($replace);
  1073. }
  1074. if ($subject instanceof Traversable) {
  1075. $subject = Arr::from($subject);
  1076. }
  1077. return $caseSensitive
  1078. ? str_replace($search, $replace, $subject)
  1079. : str_ireplace($search, $replace, $subject);
  1080. }
  1081. /**
  1082. * Replace the first occurrence of a given value in the string.
  1083. *
  1084. * @param string $search
  1085. * @param string $replace
  1086. * @param string $subject
  1087. * @return string
  1088. */
  1089. public static function replaceFirst($search, $replace, $subject)
  1090. {
  1091. $search = (string) $search;
  1092. if ($search === '') {
  1093. return $subject;
  1094. }
  1095. $position = strpos($subject, $search);
  1096. if ($position !== false) {
  1097. return substr_replace($subject, $replace, $position, strlen($search));
  1098. }
  1099. return $subject;
  1100. }
  1101. /**
  1102. * Replace the first occurrence of the given value if it appears at the start of the string.
  1103. *
  1104. * @param string $search
  1105. * @param string $replace
  1106. * @param string $subject
  1107. * @return string
  1108. */
  1109. public static function replaceStart($search, $replace, $subject)
  1110. {
  1111. $search = (string) $search;
  1112. if ($search === '') {
  1113. return $subject;
  1114. }
  1115. if (static::startsWith($subject, $search)) {
  1116. return static::replaceFirst($search, $replace, $subject);
  1117. }
  1118. return $subject;
  1119. }
  1120. /**
  1121. * Replace the last occurrence of a given value in the string.
  1122. *
  1123. * @param string $search
  1124. * @param string $replace
  1125. * @param string $subject
  1126. * @return string
  1127. */
  1128. public static function replaceLast($search, $replace, $subject)
  1129. {
  1130. $search = (string) $search;
  1131. if ($search === '') {
  1132. return $subject;
  1133. }
  1134. $position = strrpos($subject, $search);
  1135. if ($position !== false) {
  1136. return substr_replace($subject, $replace, $position, strlen($search));
  1137. }
  1138. return $subject;
  1139. }
  1140. /**
  1141. * Replace the last occurrence of a given value if it appears at the end of the string.
  1142. *
  1143. * @param string $search
  1144. * @param string $replace
  1145. * @param string $subject
  1146. * @return string
  1147. */
  1148. public static function replaceEnd($search, $replace, $subject)
  1149. {
  1150. $search = (string) $search;
  1151. if ($search === '') {
  1152. return $subject;
  1153. }
  1154. if (static::endsWith($subject, $search)) {
  1155. return static::replaceLast($search, $replace, $subject);
  1156. }
  1157. return $subject;
  1158. }
  1159. /**
  1160. * Replace the patterns matching the given regular expression.
  1161. *
  1162. * @param string|string[] $pattern
  1163. * @param (\Closure(array): string)|string[]|string $replace
  1164. * @param string[]|string $subject
  1165. * @param int $limit
  1166. * @return ($subject is array ? string[]|null : string|null)
  1167. */
  1168. public static function replaceMatches($pattern, $replace, $subject, $limit = -1)
  1169. {
  1170. if ($replace instanceof Closure) {
  1171. return preg_replace_callback($pattern, $replace, $subject, $limit);
  1172. }
  1173. return preg_replace($pattern, $replace, $subject, $limit);
  1174. }
  1175. /**
  1176. * Remove any occurrence of the given string in the subject.
  1177. *
  1178. * @param string|iterable<string> $search
  1179. * @param string|iterable<string> $subject
  1180. * @param bool $caseSensitive
  1181. * @return string
  1182. */
  1183. public static function remove($search, $subject, $caseSensitive = true)
  1184. {
  1185. if ($search instanceof Traversable) {
  1186. $search = Arr::from($search);
  1187. }
  1188. return $caseSensitive
  1189. ? str_replace($search, '', $subject)
  1190. : str_ireplace($search, '', $subject);
  1191. }
  1192. /**
  1193. * Reverse the given string.
  1194. *
  1195. * @param string $value
  1196. * @return string
  1197. */
  1198. public static function reverse(string $value)
  1199. {
  1200. return implode(array_reverse(mb_str_split($value)));
  1201. }
  1202. /**
  1203. * Begin a string with a single instance of a given value.
  1204. *
  1205. * @param string $value
  1206. * @param string $prefix
  1207. * @return ($value is '' ? ($prefix is '' ? '' : non-empty-string): non-empty-string)
  1208. */
  1209. public static function start($value, $prefix)
  1210. {
  1211. $quoted = preg_quote($prefix, '/');
  1212. return $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $value);
  1213. }
  1214. /**
  1215. * Convert the given string to upper-case.
  1216. *
  1217. * @param string $value
  1218. * @return ($value is '' ? '' : non-empty-string&uppercase-string)
  1219. */
  1220. public static function upper($value)
  1221. {
  1222. return mb_strtoupper($value, 'UTF-8');
  1223. }
  1224. /**
  1225. * Convert the given string to proper case.
  1226. *
  1227. * @param string $value
  1228. * @return string
  1229. */
  1230. public static function title($value)
  1231. {
  1232. return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
  1233. }
  1234. /**
  1235. * Convert the given string to proper case for each word.
  1236. *
  1237. * @param string $value
  1238. * @return string
  1239. */
  1240. public static function headline($value)
  1241. {
  1242. $parts = mb_split('\s+', $value);
  1243. $parts = count($parts) > 1
  1244. ? array_map(static::title(...), $parts)
  1245. : array_map(static::title(...), static::ucsplit(implode('_', $parts)));
  1246. $collapsed = static::replace(['-', '_', ' '], '_', implode('_', $parts));
  1247. return implode(' ', array_filter(explode('_', $collapsed)));
  1248. }
  1249. /**
  1250. * Get the "initials" representing each word in the provided string, optionally capitalizing.
  1251. *
  1252. * @param string $value
  1253. * @param bool $capitalize
  1254. * @return string
  1255. */
  1256. public static function initials($value, $capitalize = false)
  1257. {
  1258. $parts = mb_split("\s+", $value);
  1259. $parts = array_map(fn ($part) => mb_substr($part, 0, 1), $parts);
  1260. $initials = implode('', $parts);
  1261. return $capitalize ? static::upper($initials) : $initials;
  1262. }
  1263. /**
  1264. * Convert the given string to APA-style title case.
  1265. *
  1266. * See: https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case
  1267. *
  1268. * @param string $value
  1269. * @return string
  1270. */
  1271. public static function apa($value)
  1272. {
  1273. if (trim($value) === '') {
  1274. return $value;
  1275. }
  1276. $minorWords = [
  1277. 'and', 'as', 'but', 'for', 'if', 'nor', 'or', 'so', 'yet', 'a', 'an',
  1278. 'the', 'at', 'by', 'in', 'of', 'off', 'on', 'per', 'to', 'up', 'via',
  1279. 'et', 'ou', 'un', 'une', 'la', 'le', 'les', 'de', 'du', 'des', 'par', 'à',
  1280. ];
  1281. $endPunctuation = ['.', '!', '?', ':', '—', ','];
  1282. $words = mb_split('\s+', $value);
  1283. $wordCount = count($words);
  1284. for ($i = 0; $i < $wordCount; $i++) {
  1285. $lowercaseWord = mb_strtolower($words[$i]);
  1286. if (str_contains($lowercaseWord, '-')) {
  1287. $hyphenatedWords = explode('-', $lowercaseWord);
  1288. $hyphenatedWords = array_map(function ($part) use ($minorWords) {
  1289. return (in_array($part, $minorWords) && mb_strlen($part) <= 3)
  1290. ? $part
  1291. : mb_strtoupper(mb_substr($part, 0, 1)).mb_substr($part, 1);
  1292. }, $hyphenatedWords);
  1293. $words[$i] = implode('-', $hyphenatedWords);
  1294. } else {
  1295. if (in_array($lowercaseWord, $minorWords) &&
  1296. mb_strlen($lowercaseWord) <= 3 &&
  1297. ! ($i === 0 || in_array(mb_substr($words[$i - 1], -1), $endPunctuation))) {
  1298. $words[$i] = $lowercaseWord;
  1299. } else {
  1300. $words[$i] = mb_strtoupper(mb_substr($lowercaseWord, 0, 1)).mb_substr($lowercaseWord, 1);
  1301. }
  1302. }
  1303. }
  1304. return implode(' ', $words);
  1305. }
  1306. /**
  1307. * Get the singular form of an English word.
  1308. *
  1309. * @param string $value
  1310. * @return string
  1311. */
  1312. public static function singular($value)
  1313. {
  1314. return Pluralizer::singular($value);
  1315. }
  1316. /**
  1317. * Generate a URL friendly "slug" from a given string.
  1318. *
  1319. * @param string $title
  1320. * @param string $separator
  1321. * @param string|null $language
  1322. * @param array<string, string> $dictionary
  1323. * @return string
  1324. */
  1325. public static function slug($title, $separator = '-', $language = 'en', $dictionary = ['@' => 'at'])
  1326. {
  1327. $title = $language ? static::ascii($title, $language) : $title;
  1328. // Convert all dashes/underscores into separator
  1329. $flip = $separator === '-' ? '_' : '-';
  1330. $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
  1331. // Replace dictionary words
  1332. foreach ($dictionary as $key => $value) {
  1333. $dictionary[$key] = $separator.$value.$separator;
  1334. }
  1335. $title = str_replace(array_keys($dictionary), array_values($dictionary), $title);
  1336. // Remove all characters that are not the separator, letters, numbers, or whitespace
  1337. $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
  1338. // Replace all separator characters and whitespace by a single separator
  1339. $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
  1340. return trim($title, $separator);
  1341. }
  1342. /**
  1343. * Convert a string to snake case.
  1344. *
  1345. * @param string $value
  1346. * @param string $delimiter
  1347. * @return string
  1348. */
  1349. public static function snake($value, $delimiter = '_')
  1350. {
  1351. $key = $value;
  1352. if (isset(static::$snakeCache[$key][$delimiter])) {
  1353. return static::$snakeCache[$key][$delimiter];
  1354. }
  1355. if (! ctype_lower($value)) {
  1356. $value = preg_replace('/\s+/u', '', ucwords($value));
  1357. $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
  1358. }
  1359. return static::$snakeCache[$key][$delimiter] = $value;
  1360. }
  1361. /**
  1362. * Remove all whitespace from both ends of a string.
  1363. *
  1364. * @param string $value
  1365. * @param string|null $charlist
  1366. * @return string
  1367. */
  1368. public static function trim($value, $charlist = null)
  1369. {
  1370. if ($charlist === null) {
  1371. $trimDefaultCharacters = " \n\r\t\v\0";
  1372. return preg_replace('~^[\s'.self::INVISIBLE_CHARACTERS.$trimDefaultCharacters.']+|[\s'.self::INVISIBLE_CHARACTERS.$trimDefaultCharacters.']+$~u', '', $value) ?? trim($value);
  1373. }
  1374. return trim($value, $charlist);
  1375. }
  1376. /**
  1377. * Remove all whitespace from the beginning of a string.
  1378. *
  1379. * @param string $value
  1380. * @param string|null $charlist
  1381. * @return string
  1382. */
  1383. public static function ltrim($value, $charlist = null)
  1384. {
  1385. if ($charlist === null) {
  1386. $ltrimDefaultCharacters = " \n\r\t\v\0";
  1387. return preg_replace('~^[\s'.self::INVISIBLE_CHARACTERS.$ltrimDefaultCharacters.']+~u', '', $value) ?? ltrim($value);
  1388. }
  1389. return ltrim($value, $charlist);
  1390. }
  1391. /**
  1392. * Remove all whitespace from the end of a string.
  1393. *
  1394. * @param string $value
  1395. * @param string|null $charlist
  1396. * @return string
  1397. */
  1398. public static function rtrim($value, $charlist = null)
  1399. {
  1400. if ($charlist === null) {
  1401. $rtrimDefaultCharacters = " \n\r\t\v\0";
  1402. return preg_replace('~[\s'.self::INVISIBLE_CHARACTERS.$rtrimDefaultCharacters.']+$~u', '', $value) ?? rtrim($value);
  1403. }
  1404. return rtrim($value, $charlist);
  1405. }
  1406. /**
  1407. * Remove all "extra" blank space from the given string.
  1408. *
  1409. * @param string $value
  1410. * @return string
  1411. */
  1412. public static function squish($value)
  1413. {
  1414. return preg_replace('~(\s|\x{3164}|\x{1160})+~u', ' ', static::trim($value));
  1415. }
  1416. /**
  1417. * Determine if a given string starts with a given substring.
  1418. *
  1419. * @param string $haystack
  1420. * @param string|iterable<string> $needles
  1421. * @return ($needles is array{} ? false : ($haystack is non-empty-string ? bool : false))
  1422. *
  1423. * @phpstan-assert-if-true =non-empty-string $haystack
  1424. */
  1425. public static function startsWith($haystack, $needles)
  1426. {
  1427. if (is_null($haystack)) {
  1428. return false;
  1429. }
  1430. if (! is_iterable($needles)) {
  1431. $needles = [$needles];
  1432. }
  1433. foreach ($needles as $needle) {
  1434. if ((string) $needle !== '' && str_starts_with($haystack, $needle)) {
  1435. return true;
  1436. }
  1437. }
  1438. return false;
  1439. }
  1440. /**
  1441. * Determine if a given string doesn't start with a given substring.
  1442. *
  1443. * @param string $haystack
  1444. * @param string|iterable<string> $needles
  1445. * @return ($needles is array{} ? true : ($haystack is non-empty-string ? bool : true))
  1446. *
  1447. * @phpstan-assert-if-false =non-empty-string $haystack
  1448. */
  1449. public static function doesntStartWith($haystack, $needles)
  1450. {
  1451. return ! static::startsWith($haystack, $needles);
  1452. }
  1453. /**
  1454. * Convert a value to studly caps case.
  1455. *
  1456. * @param string $value
  1457. * @return ($value is '' ? '' : string)
  1458. */
  1459. public static function studly($value)
  1460. {
  1461. $key = $value;
  1462. if (isset(static::$studlyCache[$key])) {
  1463. return static::$studlyCache[$key];
  1464. }
  1465. $words = mb_split('\s+', static::replace(['-', '_'], ' ', $value));
  1466. $studlyWords = array_map(fn ($word) => static::ucfirst($word), $words);
  1467. return static::$studlyCache[$key] = implode($studlyWords);
  1468. }
  1469. /**
  1470. * Convert a value to Pascal case.
  1471. *
  1472. * @param string $value
  1473. * @return ($value is '' ? '' : string)
  1474. */
  1475. public static function pascal($value)
  1476. {
  1477. return static::studly($value);
  1478. }
  1479. /**
  1480. * Returns the portion of the string specified by the start and length parameters.
  1481. *
  1482. * @param string $string
  1483. * @param int $start
  1484. * @param int|null $length
  1485. * @param string $encoding
  1486. * @return string
  1487. */
  1488. public static function substr($string, $start, $length = null, $encoding = 'UTF-8')
  1489. {
  1490. return mb_substr($string, $start, $length, $encoding);
  1491. }
  1492. /**
  1493. * Returns the number of substring occurrences.
  1494. *
  1495. * @param string $haystack
  1496. * @param string $needle
  1497. * @param int $offset
  1498. * @param int|null $length
  1499. * @return int
  1500. */
  1501. public static function substrCount($haystack, $needle, $offset = 0, $length = null)
  1502. {
  1503. if (! is_null($length)) {
  1504. return substr_count($haystack, $needle, $offset, $length);
  1505. }
  1506. return substr_count($haystack, $needle, $offset);
  1507. }
  1508. /**
  1509. * Replace text within a portion of a string.
  1510. *
  1511. * @param string|string[] $string
  1512. * @param string|string[] $replace
  1513. * @param int|int[] $offset
  1514. * @param int|int[]|null $length
  1515. * @return string|string[]
  1516. */
  1517. public static function substrReplace($string, $replace, $offset = 0, $length = null)
  1518. {
  1519. if ($length === null) {
  1520. $length = static::length($string);
  1521. }
  1522. return mb_substr($string, 0, $offset)
  1523. .$replace
  1524. .mb_substr(mb_substr($string, $offset), $length);
  1525. }
  1526. /**
  1527. * Swap multiple keywords in a string with other keywords.
  1528. *
  1529. * @param array<string, string> $map
  1530. * @param string $subject
  1531. * @return string
  1532. */
  1533. public static function swap(array $map, $subject)
  1534. {
  1535. return strtr($subject, $map);
  1536. }
  1537. /**
  1538. * Take the first or last {$limit} characters of a string.
  1539. *
  1540. * @param string $string
  1541. * @param int $limit
  1542. * @return string
  1543. */
  1544. public static function take($string, int $limit): string
  1545. {
  1546. if ($limit < 0) {
  1547. return static::substr($string, $limit);
  1548. }
  1549. return static::substr($string, 0, $limit);
  1550. }
  1551. /**
  1552. * Convert the given string to Base64 encoding.
  1553. *
  1554. * @param string $string
  1555. * @return ($string is '' ? '' : string)
  1556. */
  1557. public static function toBase64($string): string
  1558. {
  1559. return base64_encode($string);
  1560. }
  1561. /**
  1562. * Decode the given Base64 encoded string.
  1563. *
  1564. * @param string $string
  1565. * @param bool $strict
  1566. * @return ($strict is true ? ($string is '' ? '' : string|false) : ($string is '' ? '' : string))
  1567. */
  1568. public static function fromBase64($string, $strict = false)
  1569. {
  1570. return base64_decode($string, $strict);
  1571. }
  1572. /**
  1573. * Make a string's first character lowercase.
  1574. *
  1575. * @param string $string
  1576. * @return ($string is '' ? '' : non-empty-string)
  1577. */
  1578. public static function lcfirst($string)
  1579. {
  1580. return static::lower(static::substr($string, 0, 1)).static::substr($string, 1);
  1581. }
  1582. /**
  1583. * Make a string's first character uppercase.
  1584. *
  1585. * @param string $string
  1586. * @return ($string is '' ? '' : non-empty-string)
  1587. */
  1588. public static function ucfirst($string)
  1589. {
  1590. return static::upper(static::substr($string, 0, 1)).static::substr($string, 1);
  1591. }
  1592. /**
  1593. * Capitalize the first character of each word in a string.
  1594. *
  1595. * @param string $string
  1596. * @param string $separators
  1597. * @return ($string is '' ? '' : non-empty-string)
  1598. */
  1599. public static function ucwords($string, $separators = " \t\r\n\f\v")
  1600. {
  1601. $pattern = '/(^|['.preg_quote($separators, '/').'])(\p{Ll})/u';
  1602. return preg_replace_callback($pattern, function ($matches) {
  1603. return $matches[1].mb_strtoupper($matches[2]);
  1604. }, $string);
  1605. }
  1606. /**
  1607. * Split a string into pieces by uppercase characters.
  1608. *
  1609. * @param string $string
  1610. * @return ($string is '' ? array{} : string[])
  1611. */
  1612. public static function ucsplit($string)
  1613. {
  1614. return preg_split('/(?=\p{Lu})/u', $string, -1, PREG_SPLIT_NO_EMPTY);
  1615. }
  1616. /**
  1617. * Get the number of words a string contains.
  1618. *
  1619. * @param string $string
  1620. * @param string|null $characters
  1621. * @return non-negative-int
  1622. */
  1623. public static function wordCount($string, $characters = null)
  1624. {
  1625. return str_word_count($string, 0, $characters);
  1626. }
  1627. /**
  1628. * Wrap a string to a given number of characters.
  1629. *
  1630. * @param string $string
  1631. * @param int $characters
  1632. * @param string $break
  1633. * @param bool $cutLongWords
  1634. * @return string
  1635. */
  1636. public static function wordWrap($string, $characters = 75, $break = "\n", $cutLongWords = false)
  1637. {
  1638. return wordwrap($string, $characters, $break, $cutLongWords);
  1639. }
  1640. /**
  1641. * Generate a UUID (version 4).
  1642. *
  1643. * @return \Ramsey\Uuid\UuidInterface
  1644. */
  1645. public static function uuid()
  1646. {
  1647. return static::$uuidFactory
  1648. ? call_user_func(static::$uuidFactory)
  1649. : Uuid::uuid4();
  1650. }
  1651. /**
  1652. * Generate a UUID (version 7).
  1653. *
  1654. * @param \DateTimeInterface|null $time
  1655. * @return \Ramsey\Uuid\UuidInterface
  1656. */
  1657. public static function uuid7($time = null)
  1658. {
  1659. return static::$uuidFactory
  1660. ? call_user_func(static::$uuidFactory)
  1661. : Uuid::uuid7($time);
  1662. }
  1663. /**
  1664. * Generate a time-ordered UUID.
  1665. *
  1666. * @return \Ramsey\Uuid\UuidInterface
  1667. */
  1668. public static function orderedUuid()
  1669. {
  1670. if (static::$uuidFactory) {
  1671. return call_user_func(static::$uuidFactory);
  1672. }
  1673. $factory = new UuidFactory;
  1674. $factory->setRandomGenerator(new CombGenerator(
  1675. $factory->getRandomGenerator(),
  1676. $factory->getNumberConverter()
  1677. ));
  1678. $factory->setCodec(new TimestampFirstCombCodec(
  1679. $factory->getUuidBuilder()
  1680. ));
  1681. return $factory->uuid4();
  1682. }
  1683. /**
  1684. * Set the callable that will be used to generate UUIDs.
  1685. *
  1686. * @param (callable(): \Ramsey\Uuid\UuidInterface)|null $factory
  1687. * @return void
  1688. */
  1689. public static function createUuidsUsing(?callable $factory = null)
  1690. {
  1691. static::$uuidFactory = $factory;
  1692. }
  1693. /**
  1694. * Set the sequence that will be used to generate UUIDs.
  1695. *
  1696. * @param \Ramsey\Uuid\UuidInterface[] $sequence
  1697. * @param (callable(): \Ramsey\Uuid\UuidInterface)|null $whenMissing
  1698. * @return void
  1699. */
  1700. public static function createUuidsUsingSequence(array $sequence, $whenMissing = null)
  1701. {
  1702. $next = 0;
  1703. $whenMissing ??= function () use (&$next) {
  1704. $factoryCache = static::$uuidFactory;
  1705. static::$uuidFactory = null;
  1706. $uuid = static::uuid();
  1707. static::$uuidFactory = $factoryCache;
  1708. $next++;
  1709. return $uuid;
  1710. };
  1711. static::createUuidsUsing(function () use (&$next, $sequence, $whenMissing) {
  1712. if (array_key_exists($next, $sequence)) {
  1713. return $sequence[$next++];
  1714. }
  1715. return $whenMissing();
  1716. });
  1717. }
  1718. /**
  1719. * Always return the same UUID when generating new UUIDs.
  1720. *
  1721. * @param (\Closure(\Ramsey\Uuid\UuidInterface): mixed)|null $callback
  1722. * @return \Ramsey\Uuid\UuidInterface
  1723. */
  1724. public static function freezeUuids(?Closure $callback = null)
  1725. {
  1726. $uuid = Str::uuid();
  1727. Str::createUuidsUsing(fn () => $uuid);
  1728. if ($callback !== null) {
  1729. try {
  1730. $callback($uuid);
  1731. } finally {
  1732. Str::createUuidsNormally();
  1733. }
  1734. }
  1735. return $uuid;
  1736. }
  1737. /**
  1738. * Indicate that UUIDs should be created normally and not using a custom factory.
  1739. *
  1740. * @return void
  1741. */
  1742. public static function createUuidsNormally()
  1743. {
  1744. static::$uuidFactory = null;
  1745. }
  1746. /**
  1747. * Generate a ULID.
  1748. *
  1749. * @param \DateTimeInterface|null $time
  1750. * @return \Symfony\Component\Uid\Ulid
  1751. */
  1752. public static function ulid($time = null)
  1753. {
  1754. if (static::$ulidFactory) {
  1755. return call_user_func(static::$ulidFactory);
  1756. }
  1757. if ($time === null) {
  1758. return new Ulid();
  1759. }
  1760. return new Ulid(Ulid::generate($time));
  1761. }
  1762. /**
  1763. * Indicate that ULIDs should be created normally and not using a custom factory.
  1764. *
  1765. * @return void
  1766. */
  1767. public static function createUlidsNormally()
  1768. {
  1769. static::$ulidFactory = null;
  1770. }
  1771. /**
  1772. * Set the callable that will be used to generate ULIDs.
  1773. *
  1774. * @param (callable(): \Symfony\Component\Uid\Ulid)|null $factory
  1775. * @return void
  1776. */
  1777. public static function createUlidsUsing(?callable $factory = null)
  1778. {
  1779. static::$ulidFactory = $factory;
  1780. }
  1781. /**
  1782. * Set the sequence that will be used to generate ULIDs.
  1783. *
  1784. * @param \Symfony\Component\Uid\Ulid[] $sequence
  1785. * @param (callable(): \Symfony\Component\Uid\Ulid)|null $whenMissing
  1786. * @return void
  1787. */
  1788. public static function createUlidsUsingSequence(array $sequence, $whenMissing = null)
  1789. {
  1790. $next = 0;
  1791. $whenMissing ??= function () use (&$next) {
  1792. $factoryCache = static::$ulidFactory;
  1793. static::$ulidFactory = null;
  1794. $ulid = static::ulid();
  1795. static::$ulidFactory = $factoryCache;
  1796. $next++;
  1797. return $ulid;
  1798. };
  1799. static::createUlidsUsing(function () use (&$next, $sequence, $whenMissing) {
  1800. if (array_key_exists($next, $sequence)) {
  1801. return $sequence[$next++];
  1802. }
  1803. return $whenMissing();
  1804. });
  1805. }
  1806. /**
  1807. * Always return the same ULID when generating new ULIDs.
  1808. *
  1809. * @param (Closure(Ulid): mixed)|null $callback
  1810. * @return Ulid
  1811. */
  1812. public static function freezeUlids(?Closure $callback = null)
  1813. {
  1814. $ulid = Str::ulid();
  1815. Str::createUlidsUsing(fn () => $ulid);
  1816. if ($callback !== null) {
  1817. try {
  1818. $callback($ulid);
  1819. } finally {
  1820. Str::createUlidsNormally();
  1821. }
  1822. }
  1823. return $ulid;
  1824. }
  1825. /**
  1826. * Remove all strings from the casing caches.
  1827. *
  1828. * @return void
  1829. */
  1830. public static function flushCache()
  1831. {
  1832. static::$snakeCache = [];
  1833. static::$camelCache = [];
  1834. static::$studlyCache = [];
  1835. }
  1836. }