helpers.php 3.0 KB

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