helpers.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. // 检查是否已存在此函数,避免重复定义
  3. if (!function_exists('getDomain')) {
  4. /**
  5. * 获取当前请求的完整域名(包括协议)
  6. *
  7. * @return string
  8. */
  9. function getDomain() {
  10. return request()->getSchemeAndHttpHost();
  11. }
  12. }
  13. if (!function_exists('getHost')) {
  14. /**
  15. * 获取当前请求的主机名
  16. *
  17. * @return string
  18. */
  19. function getHost() {
  20. return request()->getHost();
  21. }
  22. }
  23. if (!function_exists('formatDirectory')) {
  24. /**
  25. * 格式化目录名
  26. *
  27. * @param string $directory 目录名
  28. * @return string
  29. */
  30. function formatDirectory($directory) {
  31. // 如果目录名为空,返回空字符串
  32. if (empty($directory)) {
  33. return '';
  34. }
  35. // 移除前面的斜杠
  36. $directory = ltrim($directory, '/');
  37. // 确保最后添加一个斜杠
  38. $directory = rtrim($directory, '/') . '/';
  39. return $directory;
  40. }
  41. }
  42. if (!function_exists('formatAndCreateAbsoluteDirectory')) {
  43. /**
  44. * 格式化绝对路径,移除文件部分并创建目录
  45. *
  46. * @param string $path 完整的路径(可能包含文件)
  47. * @param int $permissions 新建目录的权限(默认为 0755)
  48. * @return string 格式化后的绝对路径
  49. */
  50. function formatAndCreateAbsoluteDirectory($path, $permissions = 0755) {
  51. // 如果路径为空,返回空字符串
  52. if (empty($path)) {
  53. return '';
  54. }
  55. // 确保路径是绝对路径(以 / 开头)
  56. if ($path[0] !== '/') {
  57. throw new Exception("The path must be an absolute path starting with '/'. Provided: {$path}");
  58. }
  59. // 检查是否包含文件部分
  60. if (preg_match('/\/[^\/]+\.[^\/]+$/', $path)) {
  61. // 如果路径中包含文件名,则移除
  62. $path = dirname($path);
  63. }
  64. // 确保路径以斜杠结尾
  65. $path = rtrim($path, '/') . '/';
  66. // 检查目录是否存在,如果不存在则创建
  67. if (!is_dir($path)) {
  68. if (!mkdir($path, $permissions, true)) { // true 表示递归创建中间目录
  69. throw new Exception("Failed to create directory: {$path}");
  70. }
  71. }
  72. return $path;
  73. }
  74. }
  75. if (!function_exists('generateOrderNumber')) {
  76. /**
  77. * 生成唯一订单号
  78. *
  79. * @param string $prefix 订单号前缀(可选,默认为 'ORD')
  80. * @return string
  81. */
  82. function generateOrderNumber($prefix = 'ORD') {
  83. // 获取当前日期和时间
  84. $date = date('YmdHis'); // 年月日时分秒
  85. // 生成一个随机的两位数
  86. $randomNumber = mt_rand(10, 99);
  87. // 拼接前缀、日期时间和随机数
  88. $orderNumber = $prefix . $date . $randomNumber;
  89. return $orderNumber;
  90. }
  91. }