helpers.php 2.6 KB

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