modified 优化工具类库文件

This commit is contained in:
zhaoxiang 2020-09-29 18:19:03 +08:00
parent f222973875
commit b1793c0c38
10 changed files with 118 additions and 214 deletions

View File

@ -53,6 +53,6 @@ class ExceptionHandle extends Handle
// 添加自定义异常处理机制 // 添加自定义异常处理机制
// 其他错误交给系统处理 // 其他错误交给系统处理
return parent::render($request, $e); return parent::render($request, $e)->header(config('apiadmin.CROSS_DOMAIN'));
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
declare (strict_types=1);
/** /**
* @since 2017-04-14 * @since 2017-04-14
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
@ -18,23 +19,41 @@ class ApiLogTool {
private static $userInfo = 'null'; private static $userInfo = 'null';
private static $separator = ' | '; private static $separator = ' | ';
public static function setAppInfo($data) { /**
* 设置应用信息
* @param array $data
* @author zhaoxiang <zhaoxiang051405@gmail.com>
* @desc appId|appName|deviceId
*/
public static function setAppInfo(array $data): void {
self::$appInfo = self::$appInfo =
(isset($data['app_id']) ? $data['app_id'] : 'null') . self::$separator . ($data['app_id'] ?? 'null') . self::$separator .
(isset($data['app_name']) ? $data['app_name'] : 'null') . self::$separator . ($data['app_name'] ?? 'null') . self::$separator .
(isset($data['device_id']) ? $data['device_id'] : 'null'); ($data['device_id'] ?? 'null');
} }
public static function setHeader($data) { /**
* 设置请求头日志数据
* @param array $data
* @author zhaoxiang <zhaoxiang051405@gmail.com>
* @desc accessToken|version
*/
public static function setHeader(array $data): void {
$accessToken = (isset($data['access-token']) && !empty($data['access-token'])) ? $data['access-token'] : 'null'; $accessToken = (isset($data['access-token']) && !empty($data['access-token'])) ? $data['access-token'] : 'null';
$version = (isset($data['version']) && !empty($data['version'])) ? $data['version'] : 'null'; $version = (isset($data['version']) && !empty($data['version'])) ? $data['version'] : 'null';
self::$header = $accessToken . self::$separator . $version; self::$header = $accessToken . self::$separator . $version;
} }
public static function setApiInfo($data) { /**
* 设置Api日志数据
* @param array $data
* @author zhaoxiang <zhaoxiang051405@gmail.com>
* @desc hash|apiClass
*/
public static function setApiInfo(array $data): void {
self::$apiInfo = self::$apiInfo =
(isset($data['hash']) ? $data['hash'] : 'null') . self::$separator . ($data['hash'] ?? 'null') . self::$separator .
(isset($data['api_class']) ? $data['api_class'] : 'null'); ($data['api_class'] ?? 'null');
} }
/** /**
@ -42,28 +61,44 @@ class ApiLogTool {
* @param $data * @param $data
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function setUserInfo($data) { public static function setUserInfo($data): void {
if (is_array($data) || is_object($data)) { if (is_array($data) || is_object($data)) {
$data = json_encode($data); $data = json_encode($data);
self::$userInfo = $data; self::$userInfo = $data;
} }
} }
public static function setRequest($data) { /**
* 设置请求信息
* @param $data
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
public static function setRequest($data): void {
if (is_array($data) || is_object($data)) { if (is_array($data) || is_object($data)) {
$data = json_encode($data); $data = json_encode($data);
} }
self::$request = $data; self::$request = $data;
} }
public static function setResponse($data, $code = '') { /**
* 设置返回的信息
* @param $data
* @param string $code
* @author zhaoxiang <zhaoxiang051405@gmail.com>
* @desc 返回码|数据
*/
public static function setResponse($data, string $code = ''): void {
if (is_array($data) || is_object($data)) { if (is_array($data) || is_object($data)) {
$data = json_encode($data); $data = json_encode($data);
} }
self::$response = $code . self::$separator . $data; self::$response = $code . self::$separator . $data;
} }
public static function save() { /**
* 保存接口日志数据
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
public static function save(): void {
$logPath = Env::get('runtime_path') . 'ApiLog' . DIRECTORY_SEPARATOR; $logPath = Env::get('runtime_path') . 'ApiLog' . DIRECTORY_SEPARATOR;
$logStr = implode(self::$separator, array( $logStr = implode(self::$separator, array(
'[' . date('Y-m-d H:i:s') . ']', '[' . date('Y-m-d H:i:s') . ']',
@ -81,15 +116,16 @@ class ApiLogTool {
} }
/** /**
* 保存日志文件
* @param string $log 被记录的内容 * @param string $log 被记录的内容
* @param string $type 日志文件名称 * @param string $type 日志文件名称
* @param string $filePath * @param string $filePath
*/ */
public static function writeLog($log, $type = 'sql', $filePath = '') { public static function writeLog(string $log, string $type = 'sql', string $filePath = ''): void {
if(!$filePath) { if (!$filePath) {
$filePath = Env::get('runtime_path') . DIRECTORY_SEPARATOR; $filePath = Env::get('runtime_path') . DIRECTORY_SEPARATOR;
} }
$filename = $filePath . date("Ymd") . '_' . $type . ".log"; $filename = $filePath . $type . DIRECTORY_SEPARATOR . date("YmdH") . ".log";
@$handle = fopen($filename, "a+"); @$handle = fopen($filename, "a+");
@fwrite($handle, date('Y-m-d H:i:s') . "\t" . $log . "\r\n"); @fwrite($handle, date('Y-m-d H:i:s') . "\t" . $log . "\r\n");
@fclose($handle); @fclose($handle);

View File

@ -1,104 +0,0 @@
<?php
/**
*
* @since 2019-04-23
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
namespace app\util;
class BuildName {
private $arrXing, $numbXing;
private $arrMing, $numbMing;
function __construct() {
$this->getXingList();
$this->getMingList();
}
/* 获取姓列表 */
private function getXingList() {
$this->arrXing = [
'赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋',
'沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏',
'陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭',
'郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '任', '袁', '柳', '鲍', '史', '唐', '费', '薛',
'雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '安', '常', '傅', '卞', '齐', '元', '顾', '孟',
'平', '黄', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '狄', '米', '伏', '成', '戴', '谈',
'宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '季', '贾',
'路', '娄', '江', '童', '颜', '郭', '梅', '盛', '林', '钟', '徐', '邱', '骆', '高', '夏', '蔡', '田',
'樊', '胡', '凌', '霍', '虞', '万', '支', '柯', '管', '卢', '莫', '柯', '房', '裘', '缪', '解', '应',
'宗', '丁', '宣', '邓', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '龚', '程', '嵇', '邢',
'裴', '陆', '荣', '翁', '荀', '于', '惠', '甄', '曲', '封', '储', '仲', '伊', '宁', '仇', '甘', '武',
'符', '刘', '景', '詹', '龙', '叶', '幸', '司', '黎', '溥', '印', '怀', '蒲', '邰', '从', '索', '赖',
'卓', '屠', '池', '乔', '胥', '闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵',
'冉', '宰', '雍', '桑', '寿', '通', '燕', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎',
'连', '习', '容', '向', '古', '易', '廖', '庾', '终', '步', '都', '耿', '满', '弘', '匡', '国', '文',
'寇', '广', '禄', '阙', '东', '欧', '利', '师', '巩', '聂', '关', '荆', '司马', '上官', '欧阳', '夏侯',
'诸葛', '闻人', '东方', '赫连', '皇甫', '尉迟', '公羊', '澹台', '公冶', '宗政', '濮阳', '淳于', '单于',
'太叔', '申屠', '公孙', '仲孙', '轩辕', '令狐', '徐离', '宇文', '长孙', '慕容', '司徒', '司空'];
$this->numbXing = count($this->arrXing); //姓总数
}
/* 获取名列表 */
private function getMingList() {
$this->arrMing = [
'伟', '刚', '勇', '毅', '俊', '峰', '强', '军', '平', '保', '东', '文', '辉', '力', '明', '永', '健', '世', '广', '志', '义',
'兴', '良', '海', '山', '仁', '波', '宁', '贵', '福', '生', '龙', '元', '全', '国', '胜', '学', '祥', '才', '发', '武', '新',
'利', '清', '飞', '彬', '富', '顺', '信', '子', '杰', '涛', '昌', '成', '康', '星', '光', '天', '达', '安', '岩', '中', '茂',
'进', '林', '有', '坚', '和', '彪', '博', '诚', '先', '敬', '震', '振', '壮', '会', '思', '群', '豪', '心', '邦', '承', '乐',
'绍', '功', '松', '善', '厚', '庆', '磊', '民', '友', '裕', '河', '哲', '江', '超', '浩', '亮', '政', '谦', '亨', '奇', '固',
'之', '轮', '翰', '朗', '伯', '宏', '言', '若', '鸣', '朋', '斌', '梁', '栋', '维', '启', '克', '伦', '翔', '旭', '鹏', '泽',
'晨', '辰', '士', '以', '建', '家', '致', '树', '炎', '德', '行', '时', '泰', '盛', '雄', '琛', '钧', '冠', '策', '腾', '楠',
'榕', '风', '航', '弘', '秀', '娟', '英', '华', '慧', '巧', '美', '娜', '静', '淑', '惠', '珠', '翠', '雅', '芝', '玉', '萍',
'红', '娥', '玲', '芬', '芳', '燕', '彩', '春', '菊', '兰', '凤', '洁', '梅', '琳', '素', '云', '莲', '真', '环', '雪', '荣',
'爱', '妹', '霞', '香', '月', '莺', '媛', '艳', '瑞', '凡', '佳', '嘉', '琼', '勤', '珍', '贞', '莉', '桂', '娣', '叶', '璧',
'璐', '娅', '琦', '晶', '妍', '茜', '秋', '珊', '莎', '锦', '黛', '青', '倩', '婷', '姣', '婉', '娴', '瑾', '颖', '露', '瑶',
'怡', '婵', '雁', '蓓', '纨', '仪', '荷', '丹', '蓉', '眉', '君', '琴', '蕊', '薇', '菁', '梦', '岚', '苑', '婕', '馨', '瑗',
'琰', '韵', '融', '园', '艺', '咏', '卿', '聪', '澜', '纯', '毓', '悦', '昭', '冰', '爽', '琬', '茗', '羽', '希', '欣', '飘',
'育', '滢', '馥', '筠', '柔', '竹', '霭', '凝', '晓', '欢', '霄', '枫', '芸', '菲', '寒', '伊', '亚', '宜', '可', '姬', '舒',
'影', '荔', '枝', '丽', '阳', '妮', '宝', '贝', '初', '程', '梵', '罡', '恒', '鸿', '桦', '骅', '剑', '娇', '纪', '宽', '苛',
'灵', '玛', '媚', '琪', '晴', '容', '睿', '烁', '堂', '唯', '威', '韦', '雯', '苇', '萱', '阅', '彦', '宇', '雨', '洋', '忠',
'宗', '曼', '紫', '逸', '贤', '蝶', '菡', '绿', '蓝', '儿', '翠', '烟', '小', '轩'];
//名总数
$this->numbMing = count($this->arrMing);
}
// 获取姓
private function getXing() {
// mt_rand() 比rand()方法快四倍而且生成的随机数比rand()生成的伪随机数无规律。
return $this->arrXing[mt_rand(0, $this->numbXing - 1)];
}
// 获取名字
private function getMing() {
return $this->arrMing[mt_rand(0, $this->numbMing - 1)];
}
// 获取名字
public function getName($type = 2) {
switch ($type) {
case 1: //2字
$name = $this->getXing() . $this->getMing();
break;
case 2: //随机2、3个字
$name = $this->getXing() . $this->getMing();
if (mt_rand(0, 100) > 50) $name .= $this->getMing();
break;
case 3: //只取姓
$name = $this->getXing();
break;
case 4: //只取名
$name = $this->getMing();
break;
case 0:
default: //默认情况 1姓+2名
$name = $this->getXing() . $this->getMing() . $this->getMing();
}
return $name;
}
}

View File

@ -1,24 +0,0 @@
<?php
/**
* 应用管理
* @since 2019-10-02
* @author 何秀钢 <bstdn@126.com>
*/
namespace app\util;
use Exception;
use think\exception\Handle;
/**
* Class ExceptionHandle
* @package app\util
* 异常处理handle类
* Detail see: https://www.kancloud.cn/manual/thinkphp5_1/354092
*/
class ExceptionHandle extends Handle {
public function render(Exception $e) {
return parent::render($e)->header(config('apiadmin.CROSS_DOMAIN'));
}
}

View File

@ -1,19 +0,0 @@
<?php
/**
* mock配置和ApiAdmin内置的接口返回数据配置相互转化的类
* @since 2018-08-23
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
namespace app\util;
class MockConf {
public function mockToApiAdmin() {
}
public function apiAdminToMock() {
}
}

View File

@ -1,4 +1,5 @@
<?php <?php
declare (strict_types=1);
/** /**
* 错误码统一维护 * 错误码统一维护
* @since 2017/02/28 创建 * @since 2017/02/28 创建
@ -41,8 +42,9 @@ class ReturnCode {
const UNKNOWN = -998; const UNKNOWN = -998;
const EXCEPTION = -999; const EXCEPTION = -999;
public static function getConstants() { public static function getConstants(): array {
$oClass = new \ReflectionClass(__CLASS__); $oClass = new \ReflectionClass(__CLASS__);
return $oClass->getConstants(); return $oClass->getConstants();
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
declare (strict_types=1);
/** /**
* *
* @since 2020-05-14 * @since 2020-05-14
@ -15,9 +16,12 @@ class RouterTool {
/** /**
* 构建后端路由 * 构建后端路由
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function buildAdminRouter() { public static function buildAdminRouter():void {
$methodArr = ['*', 'get', 'post', 'put', 'delete']; $methodArr = ['*', 'get', 'post', 'put', 'delete'];
$routePath = Env::get('route_path') . 'route.php'; $routePath = Env::get('route_path') . 'route.php';
$bakPath = Env::get('route_path') . 'route.bak'; $bakPath = Env::get('route_path') . 'route.bak';
@ -32,12 +36,12 @@ class RouterTool {
$context .= 'use think\facade\Route;' . PHP_EOL; $context .= 'use think\facade\Route;' . PHP_EOL;
$context .= "Route::miss('api/Miss/index');" . PHP_EOL; $context .= "Route::miss('api/Miss/index');" . PHP_EOL;
$menus = AdminMenu::all(); $menus = (new AdminMenu())->select();
if ($menus) { if ($menus) {
foreach ($menus as $menu) { foreach ($menus as $menu) {
if ($menu['url']) { if ($menu['url']) {
$context .= "Route::rule('{$menu['url']}', '{$menu['url']}', '". $context .= "Route::rule('{$menu['url']}', '{$menu['url']}', '" .
$methodArr[$menu['method']] . "')". $methodArr[$menu['method']] . "')" .
self::getAdminMiddleware($menu) . PHP_EOL; self::getAdminMiddleware($menu) . PHP_EOL;
} }
} }
@ -54,7 +58,7 @@ class RouterTool {
* @return mixed * @return mixed
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function buildVueRouter(&$menus) { public static function buildVueRouter(array &$menus): void {
foreach ($menus as $key => $menu) { foreach ($menus as $key => $menu) {
if (isset($menu['children'])) { if (isset($menu['children'])) {
foreach ($menu['children'] as $cKey => $child) { foreach ($menu['children'] as $cKey => $child) {
@ -84,16 +88,16 @@ class RouterTool {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
private static function getAdminMiddleware($menu) { private static function getAdminMiddleware(array $menu): string {
$middle = ['AdminResponse']; $middle = ['AdminResponse'];
if ($menu['log']) { if ($menu['log']) {
array_unshift($middle,'AdminLog'); array_unshift($middle, 'AdminLog');
} }
if ($menu['permission']) { if ($menu['permission']) {
array_unshift($middle,'AdminPermission'); array_unshift($middle, 'AdminPermission');
} }
if ($menu['auth']) { if ($menu['auth']) {
array_unshift($middle,'AdminAuth'); array_unshift($middle, 'AdminAuth');
} }
return '->middleware(["' . implode('", "', $middle) . '"]);'; return '->middleware(["' . implode('", "', $middle) . '"]);';

View File

@ -1,4 +1,5 @@
<?php <?php
declare (strict_types=1);
/** /**
* 构建各类有意义的随机数 * 构建各类有意义的随机数
* @since 2018-08-07 * @since 2018-08-07
@ -18,7 +19,7 @@ class StrRandom {
* @return float * @return float
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomFloat($min = -999999999, $max = 999999999, $dmin = 0, $dmax = 8) { public static function randomFloat(int $min = -999999999, int $max = 999999999, int $dmin = 0, int $dmax = 8): float {
$rand = ''; $rand = '';
$intNum = mt_rand($min, $max); $intNum = mt_rand($min, $max);
$floatLength = mt_rand($dmin, $dmax); $floatLength = mt_rand($dmin, $dmax);
@ -36,7 +37,7 @@ class StrRandom {
* @return false|string * @return false|string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomDate($format = 'Y-m-d H:i:s') { public static function randomDate(string $format = 'Y-m-d H:i:s'): string {
$timestamp = time() - mt_rand(0, 86400 * 3650); $timestamp = time() - mt_rand(0, 86400 * 3650);
return date($format, $timestamp); return date($format, $timestamp);
@ -47,7 +48,7 @@ class StrRandom {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomIp() { public static function randomIp(): string {
$ipLong = [ $ipLong = [
['607649792', '608174079'], // 36.56.0.0-36.63.255.255 ['607649792', '608174079'], // 36.56.0.0-36.63.255.255
['1038614528', '1039007743'], // 61.232.0.0-61.237.255.255 ['1038614528', '1039007743'], // 61.232.0.0-61.237.255.255
@ -70,7 +71,7 @@ class StrRandom {
* @return mixed * @return mixed
* @author zhaoxiang <zhaoxiang051405@gmail','com> * @author zhaoxiang <zhaoxiang051405@gmail','com>
*/ */
public static function randomProtocol() { public static function randomProtocol(): string {
$proArr = [ $proArr = [
'http', 'http',
'ftp', 'ftp',
@ -95,7 +96,7 @@ class StrRandom {
* 随机生成一个顶级域名 * 随机生成一个顶级域名
* @author zhaoxiang <zhaoxiang051405@gmail','com> * @author zhaoxiang <zhaoxiang051405@gmail','com>
*/ */
public static function randomTld() { public static function randomTld(): string {
$tldArr = [ $tldArr = [
'com', 'cn', 'xin', 'net', 'top', '在线', 'com', 'cn', 'xin', 'net', 'top', '在线',
'xyz', 'wang', 'shop', 'site', 'club', 'cc', 'xyz', 'wang', 'shop', 'site', 'club', 'cc',
@ -116,7 +117,7 @@ class StrRandom {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomDomain() { public static function randomDomain(): string {
$len = mt_rand(6, 16); $len = mt_rand(6, 16);
return strtolower(Strs::randString($len)) . '.' . self::randomTld(); return strtolower(Strs::randString($len)) . '.' . self::randomTld();
@ -128,7 +129,7 @@ class StrRandom {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomUrl($protocol = '') { public static function randomUrl($protocol = ''): string {
$protocol = $protocol ? $protocol : self::randomProtocol(); $protocol = $protocol ? $protocol : self::randomProtocol();
return $protocol . '://' . self::randomDomain(); return $protocol . '://' . self::randomDomain();
@ -140,7 +141,7 @@ class StrRandom {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomEmail($domain = '') { public static function randomEmail($domain = ''): string {
$len = mt_rand(6, 16); $len = mt_rand(6, 16);
$domain = $domain ? $domain : self::randomDomain(); $domain = $domain ? $domain : self::randomDomain();
@ -149,7 +150,7 @@ class StrRandom {
} }
public static function randomPhone() { public static function randomPhone(): string {
$prefixArr = [133, 153, 173, 177, 180, 181, 189, 199, 134, 135, $prefixArr = [133, 153, 173, 177, 180, 181, 189, 199, 134, 135,
136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 172, 178, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 172, 178,
182, 183, 184, 187, 188, 198, 130, 131, 132, 155, 156, 166, 182, 183, 184, 187, 188, 198, 130, 131, 132, 155, 156, 166,
@ -164,7 +165,7 @@ class StrRandom {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function randomId() { public static function randomId(): string {
$prefixArr = [ $prefixArr = [
11, 12, 13, 14, 15, 11, 12, 13, 14, 15,
21, 22, 23, 21, 22, 23,

View File

@ -1,4 +1,5 @@
<?php <?php
declare (strict_types=1);
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
@ -18,7 +19,7 @@ class Strs {
* @access public * @access public
* @return string * @return string
*/ */
public static function uuid() { public static function uuid(): string {
$charId = md5(uniqid(mt_rand(), true)); $charId = md5(uniqid(mt_rand(), true));
$hyphen = chr(45); $hyphen = chr(45);
$uuid = chr(123) $uuid = chr(123)
@ -36,7 +37,7 @@ class Strs {
* 生成Guid主键 * 生成Guid主键
* @return Boolean * @return Boolean
*/ */
public static function keyGen() { public static function keyGen(): string {
return str_replace('-', '', substr(self::uuid(), 1, -1)); return str_replace('-', '', substr(self::uuid(), 1, -1));
} }
@ -45,7 +46,7 @@ class Strs {
* @param string $string 字符串 * @param string $string 字符串
* @return Boolean * @return Boolean
*/ */
public static function isUtf8($string) { public static function isUtf8($string): bool {
$len = strlen($string); $len = strlen($string);
for ($i = 0; $i < $len; $i++) { for ($i = 0; $i < $len; $i++) {
$c = ord($string[$i]); $c = ord($string[$i]);
@ -72,15 +73,15 @@ class Strs {
/** /**
* 字符串截取,支持中文和其他编码 * 字符串截取,支持中文和其他编码
* @access public * @param string $str
* @param string $str 需要转换的字符串 * @param float $start
* @param integer $start 开始位置 * @param int $length
* @param string $length 截取长度 * @param string $charset
* @param string $charset 编码格式 * @param bool $suffix
* @param bool $suffix 截断显示字符
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function mSubStr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) { public static function mSubStr(string $str, int $length, float $start = 0, string $charset = "utf-8", bool $suffix = true): string {
if (function_exists("mb_substr")) if (function_exists("mb_substr"))
$slice = mb_substr($str, $start, $length, $charset); $slice = mb_substr($str, $start, $length, $charset);
elseif (function_exists('iconv_substr')) { elseif (function_exists('iconv_substr')) {
@ -101,12 +102,12 @@ class Strs {
* 产生随机字串,可用来自动生成密码 * 产生随机字串,可用来自动生成密码
* 默认长度6位 字母和数字混合 支持中文 * 默认长度6位 字母和数字混合 支持中文
* @param integer $len 长度 * @param integer $len 长度
* @param string $type 字串类型 * @param int $type 字串类型
* 0 字母 1 数字 其它 混合 * 0 字母 1 数字 其它 混合
* @param string $addChars 额外字符 * @param string $addChars 额外字符
* @return string * @return string
*/ */
public static function randString($len = 6, $type = '', $addChars = '') { public static function randString(int $len = 6, int $type = 0, string $addChars = ''): string {
$str = ''; $str = '';
switch ($type) { switch ($type) {
case 0: case 0:
@ -138,7 +139,7 @@ class Strs {
} else { } else {
// 中文随机字 // 中文随机字
for ($i = 0; $i < $len; $i++) { for ($i = 0; $i < $len; $i++) {
$str .= self::msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1, 'utf-8', false); $str .= self::msubstr($chars, 1, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 'utf-8', false);
} }
} }
@ -151,14 +152,14 @@ class Strs {
* @param integer $length 长度 * @param integer $length 长度
* @param integer $mode 字串类型 * @param integer $mode 字串类型
* 0 字母 1 数字 其它 混合 * 0 字母 1 数字 其它 混合
* @return string * @return array
*/ */
public static function buildCountRand($number, $length = 4, $mode = 1) { public static function buildCountRand(int $number, int $length = 4, int $mode = 1): array {
if ($mode == 1 && $length < strlen($number)) { if ($mode == 1 && $length < strlen($number)) {
//不足以生成一定数量的不重复数字 //不足以生成一定数量的不重复数字
return false; return [];
} }
$rand = array(); $rand = [];
for ($i = 0; $i < $number; $i++) { for ($i = 0; $i < $number; $i++) {
$rand[] = self::randString($length, $mode); $rand[] = self::randString($length, $mode);
} }
@ -181,10 +182,10 @@ class Strs {
* @param string $format 字符格式 * @param string $format 字符格式
* # 表示数字 * 表示字母和数字 $ 表示字母 * # 表示数字 * 表示字母和数字 $ 表示字母
* @param integer $number 生成数量 * @param integer $number 生成数量
* @return string | array * @return array
*/ */
public static function buildFormatRand($format, $number = 1) { public static function buildFormatRand(string $format, int $number = 1): array {
$str = array(); $str = [];
$length = strlen($format); $length = strlen($format);
for ($j = 0; $j < $number; $j++) { for ($j = 0; $j < $number; $j++) {
$strTemp = ''; $strTemp = '';
@ -208,7 +209,7 @@ class Strs {
$str[] = $strTemp; $str[] = $strTemp;
} }
return $number == 1 ? $strTemp : $str; return $str;
} }
/** /**
@ -217,12 +218,12 @@ class Strs {
* @param integer $max 最大值 * @param integer $max 最大值
* @return string * @return string
*/ */
public static function randNumber($min, $max) { public static function randNumber(int $min, int $max): string {
return sprintf("%0" . strlen($max) . "d", mt_rand($min, $max)); return sprintf("%0" . strlen($max) . "d", mt_rand($min, $max));
} }
// 自动转换字符集 支持数组转换 // 自动转换字符集 支持数组转换
public static function autoCharset($string, $from = 'gbk', $to = 'utf-8') { public static function autoCharset(string $string, string $from = 'gbk', string $to = 'utf-8'): string {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from; $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to; $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($string) || (is_scalar($string) && !is_string($string))) { if (strtoupper($from) === strtoupper($to) || empty($string) || (is_scalar($string) && !is_string($string))) {

View File

@ -1,4 +1,5 @@
<?php <?php
declare (strict_types=1);
/** /**
* *
* @since 2017-11-01 * @since 2017-11-01
@ -9,7 +10,13 @@ namespace app\util;
class Tools { class Tools {
public static function getDate($timestamp) { /**
* 获取相对时间
* @param int $timestamp
* @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
public static function getDate(int $timestamp): string {
$now = time(); $now = time();
$diff = $now - $timestamp; $diff = $now - $timestamp;
if ($diff <= 60) { if ($diff <= 60) {
@ -32,7 +39,7 @@ class Tools {
* @return string * @return string
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function userMd5($str, $auth_key = '') { public static function userMd5(string $str, string $auth_key = ''): string {
if (!$auth_key) { if (!$auth_key) {
$auth_key = config('apiadmin.AUTH_KEY'); $auth_key = config('apiadmin.AUTH_KEY');
} }
@ -42,11 +49,11 @@ class Tools {
/** /**
* 判断当前用户是否是超级管理员 * 判断当前用户是否是超级管理员
* @param string $uid * @param int $uid
* @return bool * @return bool
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function isAdministrator($uid = '') { public static function isAdministrator(int $uid = 0): bool {
if (!empty($uid)) { if (!empty($uid)) {
$adminConf = config('apiadmin.USER_ADMINISTRATOR'); $adminConf = config('apiadmin.USER_ADMINISTRATOR');
if (is_array($adminConf)) { if (is_array($adminConf)) {
@ -83,7 +90,7 @@ class Tools {
* @return array * @return array
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function buildArrFromObj($res, $key = '') { public static function buildArrFromObj(array $res, string $key = ''): array {
$arr = []; $arr = [];
foreach ($res as $value) { foreach ($res as $value) {
$value = $value->toArray(); $value = $value->toArray();
@ -104,7 +111,7 @@ class Tools {
* @return array * @return array
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public static function buildArrByNewKey($array, $keyName = 'id') { public static function buildArrByNewKey(array $array, string $keyName = 'id'): array {
$list = array(); $list = array();
foreach ($array as $item) { foreach ($array as $item) {
$list[$item[$keyName]] = $item; $list[$item[$keyName]] = $item;
@ -122,7 +129,7 @@ class Tools {
* @param string $root * @param string $root
* @return array * @return array
*/ */
public static function listToTree($list, $pk = 'id', $pid = 'fid', $child = 'children', $root = '0') { public static function listToTree(array $list, string $pk = 'id', string $pid = 'fid', string $child = 'children', string $root = '0'): array {
$tree = array(); $tree = array();
if (is_array($list)) { if (is_array($list)) {
$refer = array(); $refer = array();
@ -145,7 +152,7 @@ class Tools {
return $tree; return $tree;
} }
public static function formatTree($list, $lv = 0, $title = 'title') { public static function formatTree(array $list, int $lv = 0, string $title = 'title'): array {
$formatTree = array(); $formatTree = array();
foreach ($list as $key => $val) { foreach ($list as $key => $val) {
$title_prefix = ''; $title_prefix = '';