functions.php 10.6 KB
Newer Older
王源's avatar
王源 committed
1 2
<?php

3
use Hyperf\Cache\Listener\DeleteListenerEvent;
王源's avatar
王源 committed
4 5
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
6
use Hyperf\Redis\Redis;
7
use Hyperf\Utils\ApplicationContext;
8 9
use Psr\EventDispatcher\EventDispatcherInterface;

王源's avatar
王源 committed
10 11 12 13 14

/**
 * 容器实例
 */
if (!function_exists('container')) {
王源's avatar
王源 committed
15
    function container($key = null)
王源's avatar
王源 committed
16
    {
王源's avatar
王源 committed
17 18 19 20 21
        if (is_null($key)) {
            return ApplicationContext::getContainer();
        } else {
            return ApplicationContext::getContainer()->get($key);
        }
王源's avatar
王源 committed
22 23 24 25
    }
}

if (!function_exists('redis')) {
26 27 28 29
    /**
     * 获取redis客户端实例
     * @return Redis|mixed
     */
王源's avatar
王源 committed
30 31
    function redis()
    {
王源's avatar
王源 committed
32
        return container(Redis::class);
王源's avatar
王源 committed
33 34 35
    }
}

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/**
 * token
 */
if (!function_exists('token')) {
    function token()
    {
        $token = request()->getHeader('Authorization')[0] ?? '';
        if (strlen($token) > 0) {
            $token = ucfirst($token);
            $arr = explode('Bearer ', $token);
            $token = $arr[1] ?? '';
            if (strlen($token) > 0) {
                return $token;
            }
        }
        return false;
    }
}

王源's avatar
王源 committed
55 56 57 58 59 60 61 62 63 64
if (!function_exists('request')) {
    /**
     * 请求实例
     * @param array|string|null $key
     * @param mixed $default
     * @return RequestInterface|string|array|mixed
     */
    function request($key = null, $default = null)
    {
        if (is_null($key)) {
王源's avatar
王源 committed
65
            return container(RequestInterface::class);
王源's avatar
王源 committed
66 67 68
        }

        if (is_array($key)) {
王源's avatar
王源 committed
69
            return container(RequestInterface::class)->inputs($key);
王源's avatar
王源 committed
70 71
        }

王源's avatar
王源 committed
72
        $value = container(RequestInterface::class)->input($key);
王源's avatar
王源 committed
73 74 75 76 77 78

        return is_null($value) ? value($default) : $value;
    }
}

if (!function_exists('response')) {
79 80 81 82
    /**
     * 响应实例
     * @return mixed|ResponseInterface
     */
王源's avatar
王源 committed
83 84
    function response()
    {
王源's avatar
王源 committed
85
        return container(ResponseInterface::class);
王源's avatar
王源 committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    }
}

if (!function_exists('success')) {
    /**
     * 成功响应实例
     * @param string $msg
     * @param mixed $data
     * @param int $code
     * @return mixed
     */
    function success($msg = '', $data = null, $code = 200)
    {
        return response()->json([
            'msg' => $msg,
            'data' => $data,
            'code' => $code
        ]);
    }
}

if (!function_exists('fail')) {
    /**
     * 失败响应实例
     * @param string $msg
     * @param mixed $data
     * @param int $code
     * @return mixed
     */
    function fail($msg = '', $data = null, $code = 400)
    {
        return response()->json([
            'msg' => $msg,
            'data' => $data,
            'code' => $code
        ]);
    }
}

王源's avatar
王源 committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
if (!function_exists('decimal_to_abc')) {
    /**
     * 数字转换对应26个字母
     * @param $num
     * @return string
     */
    function decimal_to_abc($num)
    {
        $str = "";
        $ten = $num;
        if ($ten == 0) return "A";
        while ($ten != 0) {
            $x = $ten % 26;
            $str .= chr(65 + $x);
            $ten = intval($ten / 26);
        }
        return strrev($str);
    }
}

if (!function_exists('diff_between_two_days')) {
    /**
     * 计算两个日期之间相差的天数
     * @param $day1
     * @param $day2
     * @return float|int
     */
    function diff_between_two_days($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);
        return round((abs($second1 - $second2) / 86400), 0);
    }
}

if (!function_exists('decimals_to_percentage')) {
    /**
     * 将小数转换百分数
     * @param float $decimals 小数
     * @param int $num 保留小数位
     * @return string
     */
    function decimals_to_percentage($decimals, $num = 2)
    {
        return sprintf("%01." . $num . "f", $decimals * 100) . '%';
    }
}

if (!function_exists('calculate_grade')) {
    /**
     *
     * 计算一个数的区间范围等级
     * @param array $range 区间范围(从大到小排列)
     * @param $num
     * @return mixed|void
     */
    function calculate_grade($range, $num)
    {
        $max = max($range);
        if ($num >= $max) {
            return count($range);
        }
        foreach ($range as $k => $v) {
            if ($num < $v) {
                return $k;
            }
        }
    }
}

if (!function_exists('convertAmountToCn')) {
    /**
     * 2  * 将数值金额转换为中文大写金额
     * 3  * @param $amount float 金额(支持到分)
     * 4  * @param $type   int   补整类型,0:到角补整;1:到元补整
     * 5  * @return mixed 中文大写金额
     * 6  */
    function convertAmountToCn($amount, $type = 1)
    {
        // 判断输出的金额是否为数字或数字字符串
        if (!is_numeric($amount)) {
            return "要转换的金额只能为数字!";
        }

        // 金额为0,则直接输出"零元整"
        if ($amount == 0) {
            return "人民币零元整";
        }

        // 金额不能为负数
        if ($amount < 0) {
            return "要转换的金额不能为负数!";
        }

        // 金额不能超过万亿,即12位
        if (strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }

        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');

        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);

        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);

        // 将整数部分替换成大写汉字
        $result = '人民币';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        for ($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if ($integerArr[$i] != 0) {
                $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            } else {
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) {
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }

        // 如果小数位也要转换
        if ($type == 0) {
            // 将小数位的数值字符串拆分成数组
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if ($decimalArr[0] != 0) {
                $result = $result . $digital[$decimalArr[0]] . '角';
            }
            // 将分替换成大写汉字. 如果为0,则不替换
            if ($decimalArr[1] != 0) {
                $result = $result . $digital[$decimalArr[1]] . '分';
            }
        } else {
            $result = $result . '整';
        }
        return $result;
    }
}

if (!function_exists('today')) {
    /**
     * Create a new Carbon instance for the current time.
     * @return false|string
     */
    function today()
    {
        return date('Y-m-d', time());
    }
}

if (!function_exists('now')) {
    /**
     * Create a new Carbon instance for the current time.
     * @return false|string
     */
    function now()
    {
        return date('Y-m-d h:i:s', time());
    }
}
王源's avatar
王源 committed
291 292 293

if (!function_exists('get_tree_id')) {
    /**
294 295
     * @param array $array
     * @param array $pid
王源's avatar
王源 committed
296 297
     * @return array
     */
298
    function get_tree_id(array $array, $pids = [0])
王源's avatar
王源 committed
299
    {
300
        $list = [];
王源's avatar
王源 committed
301
        foreach ($array as $key => $value) {
302
            if (in_array($value['pid'], $pids) || in_array($value['id'], $pids)) {
王源's avatar
王源 committed
303 304 305 306
                $list[] = $value['id'];
                unset($array[$key]);
            }
        }
307 308 309
        if ($list == []) return [];
        $children = get_tree_id($array, $list);
        return array_merge($list, $children);
王源's avatar
王源 committed
310 311 312
    }
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
if (!function_exists('get_tree')) {
    /**
     * 树状的算法
     * @param array $array 代转化数组
     * @param int $pid 起始节点
     * @return array
     */
    function get_tree($array = [], $pid = 0)
    {
        $list = [];
        // 获取每个节点的直属子节点,*记住是直属,不是所有子节点
        foreach ($array as $item) {
            if (isset($list[$item['pid']])) {
                $list[$item['pid']][] = $item;
            } else {
                $list[$item['pid']] = [$item];
            }
        }
        return format_tree($list);
    }
}
王源's avatar
王源 committed
334

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
if (!function_exists('format_tree')) {
    /**
     * 利用递归格式化每个节点
     * @param array $array 代转化数组
     * @param int $pid 起始节点
     * @return array
     */
    function format_tree(array $array = [], $pid = 0)
    {
        $result = [];
        if (!isset($array[$pid])) {
            return $result;
        }
        foreach ($array[$pid] as $item) {
            $item['children'] = format_tree($array, $item['id']);
            array_push($result, $item);
        }
        return $result;
    }
}
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

if (!function_exists('flushAnnotationCache')) {
    /**
     * 刷新注解缓存,清楚注解缓存
     * @param string $listener
     * @param mixed $keys
     * @return bool
     */
    function flushAnnotationCache($listener, $keys)
    {
        $keys = is_array($keys) ? $keys : [$keys];
        $dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class);
        foreach ($keys as $key) {
            $dispatcher->dispatch(new DeleteListenerEvent($listener, [$key]));
        }
        return true;
    }
}
373 374 375 376 377 378 379 380 381 382

if (!function_exists('num_2_file_size')) {
    /**
     * 数字转文件大小
     * @param $num
     * @return string
     */
    function num_2_file_size($num)
    {
        $p = 0;
383
        $format = 'B';
384 385 386 387
        if ($num > 0 && $num < 1024) {
            return number_format($num) . ' ' . $format;
        } else if ($num >= 1024 && $num < pow(1024, 2)) {
            $p = 1;
388
            $format = 'KB';
389 390
        } else if ($num >= pow(1024, 2) && $num < pow(1024, 3)) {
            $p = 2;
391
            $format = 'MB';
392 393
        } else if ($num >= pow(1024, 3) && $num < pow(1024, 4)) {
            $p = 3;
394 395 396
            $format = 'GB';
        } else if ($num >= pow(1024, 4) && $num < pow(1024, 5)) {
            $p = 4;
397 398 399 400 401 402
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 2) . ' ' . $format;
    }
}