helpers.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. use Carbon\CarbonInterval;
  3. const MiB = 1048576;
  4. const GiB = 1073741824;
  5. const Minute = 60;
  6. const Hour = 3600;
  7. const Day = 86400;
  8. const Mbps = 125000;
  9. // base64加密(处理URL)
  10. if (! function_exists('base64url_encode')) {
  11. function base64url_encode(string $data): string
  12. {
  13. return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
  14. }
  15. }
  16. // base64解密(处理URL)
  17. if (! function_exists('base64url_decode')) {
  18. function base64url_decode(string $data): false|string
  19. {
  20. return base64_decode(str_replace(['-', '_'], ['+', '/'], $data));
  21. }
  22. }
  23. // 根据流量值自动转换单位输出
  24. if (! function_exists('formatBytes')) {
  25. function formatBytes(int $bytes, ?string $base = null, int $precision = 2): string
  26. {
  27. $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  28. $bytes = max($bytes, 0);
  29. $power = floor(($bytes ? log($bytes) : 0) / log(1024));
  30. $power = min($power, count($units) - 1);
  31. $bytes /= 1024 ** $power;
  32. if ($base) {
  33. $power += max(array_search($base, $units), 0);
  34. }
  35. return round($bytes, $precision).' '.$units[$power];
  36. }
  37. }
  38. // 秒转时间
  39. if (! function_exists('formatTime')) {
  40. function formatTime(int $seconds): string
  41. {
  42. $interval = CarbonInterval::seconds($seconds);
  43. return $interval->cascade()->forHumans();
  44. }
  45. }
  46. // 获取系统设置
  47. if (! function_exists('sysConfig')) {
  48. function sysConfig(?string $key = null, ?string $default = null): array|string|null
  49. {
  50. return $key ? config("settings.$key", $default) : config('settings');
  51. }
  52. }
  53. // Array values and indexes clean
  54. if (! function_exists('array_clean')) {
  55. function array_clean(array &$array): array
  56. {
  57. foreach ($array as $key => &$value) {
  58. if (is_array($value)) {
  59. $value = array_clean($value);
  60. }
  61. if (empty($value)) {
  62. unset($array[$key]);
  63. }
  64. }
  65. return $array;
  66. }
  67. }
  68. // string url safe sanitize
  69. if (! function_exists('string_urlsafe')) {
  70. function string_urlsafe($string, $force_lowercase = true, $anal = false): string
  71. {
  72. $clean = preg_replace('/[~`!@#$%^&*()_=+\[\]{}\\|;:"\'<>,.?\/]/', '_', strip_tags($string));
  73. $clean = preg_replace('/\s+/', '-', $clean);
  74. $clean = ($anal) ? preg_replace('/[^a-zA-Z0-9]/', '', $clean) : $clean;
  75. if ($force_lowercase) {
  76. $clean = function_exists('mb_strtolower') ? mb_strtolower($clean, 'UTF-8') : strtolower($clean);
  77. }
  78. return $clean;
  79. }
  80. }