PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/blog/vendor/laravel/framework/src/Illuminate/Support/Str.php

https://gitlab.com/zan_zan/laravel_sample
PHP | 436 lines | 187 code | 66 blank | 183 comment | 27 complexity | cff71591c0f85133ad684b7a4bab9660 MD5 | raw file
  1. <?php
  2. namespace Illuminate\Support;
  3. use RuntimeException;
  4. use Stringy\StaticStringy;
  5. use Illuminate\Support\Traits\Macroable;
  6. class Str
  7. {
  8. use Macroable;
  9. /**
  10. * The cache of snake-cased words.
  11. *
  12. * @var array
  13. */
  14. protected static $snakeCache = [];
  15. /**
  16. * The cache of camel-cased words.
  17. *
  18. * @var array
  19. */
  20. protected static $camelCache = [];
  21. /**
  22. * The cache of studly-cased words.
  23. *
  24. * @var array
  25. */
  26. protected static $studlyCache = [];
  27. /**
  28. * Transliterate a UTF-8 value to ASCII.
  29. *
  30. * @param string $value
  31. * @return string
  32. */
  33. public static function ascii($value)
  34. {
  35. return StaticStringy::toAscii($value);
  36. }
  37. /**
  38. * Convert a value to camel case.
  39. *
  40. * @param string $value
  41. * @return string
  42. */
  43. public static function camel($value)
  44. {
  45. if (isset(static::$camelCache[$value])) {
  46. return static::$camelCache[$value];
  47. }
  48. return static::$camelCache[$value] = lcfirst(static::studly($value));
  49. }
  50. /**
  51. * Determine if a given string contains a given substring.
  52. *
  53. * @param string $haystack
  54. * @param string|array $needles
  55. * @return bool
  56. */
  57. public static function contains($haystack, $needles)
  58. {
  59. foreach ((array) $needles as $needle) {
  60. if ($needle != '' && strpos($haystack, $needle) !== false) {
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. /**
  67. * Determine if a given string ends with a given substring.
  68. *
  69. * @param string $haystack
  70. * @param string|array $needles
  71. * @return bool
  72. */
  73. public static function endsWith($haystack, $needles)
  74. {
  75. foreach ((array) $needles as $needle) {
  76. if ((string) $needle === substr($haystack, -strlen($needle))) {
  77. return true;
  78. }
  79. }
  80. return false;
  81. }
  82. /**
  83. * Cap a string with a single instance of a given value.
  84. *
  85. * @param string $value
  86. * @param string $cap
  87. * @return string
  88. */
  89. public static function finish($value, $cap)
  90. {
  91. $quoted = preg_quote($cap, '/');
  92. return preg_replace('/(?:'.$quoted.')+$/', '', $value).$cap;
  93. }
  94. /**
  95. * Determine if a given string matches a given pattern.
  96. *
  97. * @param string $pattern
  98. * @param string $value
  99. * @return bool
  100. */
  101. public static function is($pattern, $value)
  102. {
  103. if ($pattern == $value) {
  104. return true;
  105. }
  106. $pattern = preg_quote($pattern, '#');
  107. // Asterisks are translated into zero-or-more regular expression wildcards
  108. // to make it convenient to check if the strings starts with the given
  109. // pattern such as "library/*", making any string check convenient.
  110. $pattern = str_replace('\*', '.*', $pattern).'\z';
  111. return (bool) preg_match('#^'.$pattern.'#', $value);
  112. }
  113. /**
  114. * Return the length of the given string.
  115. *
  116. * @param string $value
  117. * @return int
  118. */
  119. public static function length($value)
  120. {
  121. return mb_strlen($value);
  122. }
  123. /**
  124. * Limit the number of characters in a string.
  125. *
  126. * @param string $value
  127. * @param int $limit
  128. * @param string $end
  129. * @return string
  130. */
  131. public static function limit($value, $limit = 100, $end = '...')
  132. {
  133. if (mb_strwidth($value, 'UTF-8') <= $limit) {
  134. return $value;
  135. }
  136. return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
  137. }
  138. /**
  139. * Convert the given string to lower-case.
  140. *
  141. * @param string $value
  142. * @return string
  143. */
  144. public static function lower($value)
  145. {
  146. return mb_strtolower($value);
  147. }
  148. /**
  149. * Limit the number of words in a string.
  150. *
  151. * @param string $value
  152. * @param int $words
  153. * @param string $end
  154. * @return string
  155. */
  156. public static function words($value, $words = 100, $end = '...')
  157. {
  158. preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $value, $matches);
  159. if (!isset($matches[0]) || strlen($value) === strlen($matches[0])) {
  160. return $value;
  161. }
  162. return rtrim($matches[0]).$end;
  163. }
  164. /**
  165. * Parse a Class@method style callback into class and method.
  166. *
  167. * @param string $callback
  168. * @param string $default
  169. * @return array
  170. */
  171. public static function parseCallback($callback, $default)
  172. {
  173. return static::contains($callback, '@') ? explode('@', $callback, 2) : [$callback, $default];
  174. }
  175. /**
  176. * Get the plural form of an English word.
  177. *
  178. * @param string $value
  179. * @param int $count
  180. * @return string
  181. */
  182. public static function plural($value, $count = 2)
  183. {
  184. return Pluralizer::plural($value, $count);
  185. }
  186. /**
  187. * Generate a more truly "random" alpha-numeric string.
  188. *
  189. * @param int $length
  190. * @return string
  191. *
  192. * @throws \RuntimeException
  193. */
  194. public static function random($length = 16)
  195. {
  196. $string = '';
  197. while (($len = strlen($string)) < $length) {
  198. $size = $length - $len;
  199. $bytes = static::randomBytes($size);
  200. $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
  201. }
  202. return $string;
  203. }
  204. /**
  205. * Generate a more truly "random" bytes.
  206. *
  207. * @param int $length
  208. * @return string
  209. *
  210. * @throws \RuntimeException
  211. */
  212. public static function randomBytes($length = 16)
  213. {
  214. if (PHP_MAJOR_VERSION >= 7) {
  215. $bytes = random_bytes($length);
  216. } elseif (function_exists('openssl_random_pseudo_bytes')) {
  217. $bytes = openssl_random_pseudo_bytes($length, $strong);
  218. if ($bytes === false || $strong === false) {
  219. throw new RuntimeException('Unable to generate random string.');
  220. }
  221. } else {
  222. throw new RuntimeException('OpenSSL extension is required for PHP 5 users.');
  223. }
  224. return $bytes;
  225. }
  226. /**
  227. * Generate a "random" alpha-numeric string.
  228. *
  229. * Should not be considered sufficient for cryptography, etc.
  230. *
  231. * @param int $length
  232. * @return string
  233. */
  234. public static function quickRandom($length = 16)
  235. {
  236. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  237. return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
  238. }
  239. /**
  240. * Compares two strings using a constant-time algorithm.
  241. *
  242. * Note: This method will leak length information.
  243. *
  244. * Note: Adapted from Symfony\Component\Security\Core\Util\StringUtils.
  245. *
  246. * @param string $knownString
  247. * @param string $userInput
  248. * @return bool
  249. */
  250. public static function equals($knownString, $userInput)
  251. {
  252. if (!is_string($knownString)) {
  253. $knownString = (string) $knownString;
  254. }
  255. if (!is_string($userInput)) {
  256. $userInput = (string) $userInput;
  257. }
  258. if (function_exists('hash_equals')) {
  259. return hash_equals($knownString, $userInput);
  260. }
  261. $knownLength = mb_strlen($knownString);
  262. if (mb_strlen($userInput) !== $knownLength) {
  263. return false;
  264. }
  265. $result = 0;
  266. for ($i = 0; $i < $knownLength; ++$i) {
  267. $result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
  268. }
  269. return 0 === $result;
  270. }
  271. /**
  272. * Convert the given string to upper-case.
  273. *
  274. * @param string $value
  275. * @return string
  276. */
  277. public static function upper($value)
  278. {
  279. return mb_strtoupper($value);
  280. }
  281. /**
  282. * Convert the given string to title case.
  283. *
  284. * @param string $value
  285. * @return string
  286. */
  287. public static function title($value)
  288. {
  289. return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
  290. }
  291. /**
  292. * Get the singular form of an English word.
  293. *
  294. * @param string $value
  295. * @return string
  296. */
  297. public static function singular($value)
  298. {
  299. return Pluralizer::singular($value);
  300. }
  301. /**
  302. * Generate a URL friendly "slug" from a given string.
  303. *
  304. * @param string $title
  305. * @param string $separator
  306. * @return string
  307. */
  308. public static function slug($title, $separator = '-')
  309. {
  310. $title = static::ascii($title);
  311. // Convert all dashes/underscores into separator
  312. $flip = $separator == '-' ? '_' : '-';
  313. $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
  314. // Remove all characters that are not the separator, letters, numbers, or whitespace.
  315. $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));
  316. // Replace all separator characters and whitespace by a single separator
  317. $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
  318. return trim($title, $separator);
  319. }
  320. /**
  321. * Convert a string to snake case.
  322. *
  323. * @param string $value
  324. * @param string $delimiter
  325. * @return string
  326. */
  327. public static function snake($value, $delimiter = '_')
  328. {
  329. $key = $value.$delimiter;
  330. if (isset(static::$snakeCache[$key])) {
  331. return static::$snakeCache[$key];
  332. }
  333. if (!ctype_lower($value)) {
  334. $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1'.$delimiter, $value));
  335. $value = preg_replace('/\s+/', '', $value);
  336. }
  337. return static::$snakeCache[$key] = $value;
  338. }
  339. /**
  340. * Determine if a given string starts with a given substring.
  341. *
  342. * @param string $haystack
  343. * @param string|array $needles
  344. * @return bool
  345. */
  346. public static function startsWith($haystack, $needles)
  347. {
  348. foreach ((array) $needles as $needle) {
  349. if ($needle != '' && strpos($haystack, $needle) === 0) {
  350. return true;
  351. }
  352. }
  353. return false;
  354. }
  355. /**
  356. * Convert a value to studly caps case.
  357. *
  358. * @param string $value
  359. * @return string
  360. */
  361. public static function studly($value)
  362. {
  363. $key = $value;
  364. if (isset(static::$studlyCache[$key])) {
  365. return static::$studlyCache[$key];
  366. }
  367. $value = ucwords(str_replace(['-', '_'], ' ', $value));
  368. return static::$studlyCache[$key] = str_replace(' ', '', $value);
  369. }
  370. }