Tool.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Leo
  5. * Date: 2017/9/3
  6. * Time: 下午10:05
  7. */
  8. namespace common\helpers;
  9. use common\models\AlarmCall;
  10. use Faker\Provider\Uuid;
  11. use yii\base\Exception;
  12. use yii\helpers\Url;
  13. use yii\httpclient\Client;
  14. class Tool {
  15. /**
  16. * 获取无限级树形分类
  17. * @param array $cate
  18. * @param int $pid
  19. * @param int $level
  20. * @param string $html
  21. * @return array
  22. */
  23. public static function categoryTree(array $cate, $pid=0, $level=0, $html='--') {
  24. $tree = [];
  25. foreach ($cate as $key=>$value){
  26. if($value['pid'] == $pid) {
  27. $value['level'] = $level + 1;
  28. $html = str_repeat($html,$value['level']);
  29. $tree[] = $value;
  30. $tree = array_merge($tree, self::categoryTree($cate,$value['id'],$level+1,$html));
  31. }
  32. }
  33. return $tree;
  34. }
  35. /**
  36. * 解析数据
  37. * @param $args
  38. * @param null $defaults
  39. * @return array
  40. */
  41. public static function deepParse($args, $defaults = NULL){
  42. $result = array();
  43. if (is_object($args)){
  44. $result = get_object_vars( $args );
  45. } elseif (is_array($args)){
  46. $result =& $args;
  47. }else{
  48. parse_str($args, $result);
  49. }
  50. if (is_array($defaults))
  51. return array_merge($defaults, $result);
  52. return $result;
  53. }
  54. /**
  55. * 格式化金额,保留两位小数
  56. * @param $price
  57. * @param int $auto 是否自动四舍五入
  58. * @return string
  59. */
  60. public static function formatPrice($price ,$auto = 1){
  61. if(!$price) return '0.00';
  62. if($auto==1){
  63. return sprintf("%.2f", $price);
  64. }else{
  65. return substr(sprintf("%.3f",$price),0,-1);
  66. }
  67. }
  68. // 格式化业绩期
  69. public static function formatPreparePerf($perf) {
  70. return number_format($perf,2);
  71. }
  72. /**
  73. * 前台业绩格式化
  74. * @param $perf
  75. * @param int $auto
  76. * @param int $zoom
  77. * @return bool|string
  78. */
  79. public static function formatFrontPerf($perf, $auto = 0, $zoom = 100) {
  80. if (!$perf) return '0.00';
  81. $perf = $perf / $zoom;
  82. if ($auto == 1) {
  83. return sprintf("%.2f", $perf);
  84. } else {
  85. return substr(sprintf("%.3f", $perf), 0, -1);
  86. }
  87. }
  88. /**
  89. * 格式化结算奖金
  90. * @param $calcBonus
  91. * @return string
  92. */
  93. public static function formatCalcBonus($calcBonus) {
  94. return sprintf("%.3f", $calcBonus);
  95. }
  96. /**
  97. * 获得文件扩展名
  98. * @param $file
  99. * @return string
  100. */
  101. public static function getExt($file) {
  102. $ext = pathinfo($file ,PATHINFO_EXTENSION);
  103. return strtolower($ext);
  104. }
  105. /**
  106. * 获取文件上传的地址
  107. * @return string
  108. */
  109. public static function getUploadUrl(){
  110. return \Yii::getAlias('@frontendUrl').'/'.\Yii::$app->params['upload']['dir'];
  111. }
  112. /**
  113. * 对二维数组排序
  114. *
  115. * @param $arrays
  116. * @param $sortField
  117. * @param int $sortOrder
  118. * @param int $sortType
  119. * @return bool
  120. */
  121. public static function sortMultiArray($arrays, $sortField, $sortOrder = SORT_ASC, $sortType = SORT_NUMERIC){
  122. if(is_array($arrays)){
  123. foreach ($arrays as $array){
  124. if(is_array($array)){
  125. $key_arrays[] = $array[$sortField];
  126. }else{
  127. return false;
  128. }
  129. }
  130. }else{
  131. return false;
  132. }
  133. array_multisort($key_arrays,$sortOrder,$sortType,$arrays);
  134. return $arrays;
  135. }
  136. /**
  137. * 清除字符串中的所有空格
  138. * @param $string
  139. * @return mixed
  140. */
  141. public static function trimAll($string){
  142. $waitClean=array(" "," ");
  143. $cleaned=array("","");
  144. return str_replace($waitClean,$cleaned,$string);
  145. }
  146. /**
  147. * 去除两端的逗号和所有空格
  148. * @param $string
  149. * @return mixed|string
  150. */
  151. public static function trimCommaAndSpace($string){
  152. $result = self::trimAll($string);
  153. $result = trim($result, ',');
  154. return $result;
  155. }
  156. /**
  157. * 页面跳转
  158. * @param string $url
  159. * @param string $err
  160. * @param bool $parent
  161. * @return string
  162. */
  163. public static function jsJump($url = 'back' ,$err = '' ,$parent = false) {
  164. $output = '<script type="text/javascript">';
  165. if (!empty($err)) $output .= "alert('{$err}');";
  166. ('back' == $url)
  167. ? $output .= 'window.history.go(-1);'
  168. : ($output .= ($parent == true ? 'parent.' : '') . 'location.href="' . $url . '";');
  169. $output .= '</script>';
  170. return $output;
  171. }
  172. /**
  173. * 发送Curl请求
  174. * @param $method
  175. * @param $url
  176. * @param array $data
  177. * @return \yii\httpclient\Response
  178. * @throws \yii\httpclient\Exception
  179. */
  180. public static function sendCurlRequest($method, $url, $data = []){
  181. $client = new Client();
  182. $request = $client->createRequest()
  183. ->setHeaders(['content-type' => 'application/json'])
  184. ->addHeaders(['user-agent' => 'bonusSystem'])
  185. ->setFormat(Client::FORMAT_JSON)
  186. ->setMethod($method)
  187. ->setUrl($url);
  188. if(!empty($data)){
  189. $request->setData($data);
  190. }
  191. return $request->send();
  192. }
  193. /**
  194. * 数字补齐
  195. * @param $num
  196. * @param int $bit
  197. * @param string $fixStr
  198. * @return string
  199. */
  200. public static function numFix($num, $bit = 2, $fixStr = '0'){
  201. return str_pad(intval($num),$bit,$fixStr,STR_PAD_LEFT);
  202. }
  203. /**
  204. * 替换手机号为隐藏格式
  205. * @param $str
  206. * @return null|string|string[]
  207. */
  208. public static function hideMobile($str){
  209. return preg_replace('/^(\d{3})\d{4}(\d{4})$/', '${1}****${2}', $str);
  210. }
  211. /**
  212. * 替换身份证为隐藏格式
  213. * @param $str
  214. * @return null|string|string[]
  215. */
  216. public static function hideIdCard($str){
  217. return preg_replace('/^(\d{3})\d{3}(\d{4})\d{8}$/', '${1}***${2}********', $str);
  218. }
  219. /**
  220. * 替换银行卡号隐藏格式
  221. * @param $str
  222. * @return null|string|string[]
  223. */
  224. public static function hideBankNo($str){
  225. if(preg_match('/^(\d{4})\d{11}(\d{4})$/', $str)){
  226. return preg_replace('/^(\d{4})\d{11}(\d{4})$/', '${1}***********${2}', $str);
  227. } elseif(preg_match('/^(\d{4})\d{8}(\d{4})$/', $str)){
  228. return preg_replace('/^(\d{4})\d{8}(\d{4})$/', '${1}********${2}', $str);
  229. } else {
  230. return $str;
  231. }
  232. }
  233. /**
  234. * 清空目录下的所有文件
  235. * @param $dir
  236. * @throws Exception
  237. */
  238. public static function clearDir($dir){
  239. $dirHandle = opendir( $dir );
  240. if($dirHandle === false){
  241. throw new Exception('打开目录失败');
  242. }
  243. while( ($file = readdir( $dirHandle )) !== false ){
  244. if ( $file != '.' && $file != '..' && $file != '.gitignore' ) {
  245. unlink( $dir . '/' . $file );
  246. }
  247. }
  248. }
  249. /**
  250. * 过滤特殊字符
  251. * @param $strParam
  252. * @return string|string[]|null
  253. */
  254. public static function filterSpecialChar($strParam){
  255. $regex = "/\/|\~|\,|\。|\!|\?|\“|\”|\【|\】|\『|\』|\:|\;|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
  256. return preg_replace($regex,"",$strParam);
  257. }
  258. public static function allow_area($area, $search) {
  259. $result = false;
  260. foreach ($search as $key => $value) {
  261. $count = count($value);
  262. //不够三项的,补充到三项
  263. if ($count < 3) {
  264. $num = 3 - $count;
  265. $value += array_fill($count, $num, '');
  266. }
  267. if ($value[0] == '') { //说明地区选的全部
  268. $result = true;
  269. break;
  270. }
  271. if ($value[0] == $area[0] && ($value[1] == '' || $value[1] == $area[1]) && ($value[2] == '' || $value[2] == $area[2])) {
  272. $result = true;
  273. break;
  274. }
  275. }
  276. return $result;
  277. }
  278. /**
  279. * 转驼峰
  280. * @param $words
  281. * @param string $separator
  282. * @return string
  283. */
  284. public static function toCamelize( $words , $separator = '_') {
  285. if(!$words){
  286. return '';
  287. }
  288. $words = $separator. str_replace($separator, " ", strtolower($words));
  289. return ltrim(str_replace(" ", "", ucwords($words)), $separator );
  290. }
  291. public static function isConsoleApp(){
  292. return (\Yii::$app->id == 'app-console');
  293. }
  294. /**
  295. * 根据KEY合并两个数组
  296. * @param $arr1
  297. * @param $arr2
  298. * @param array $keyArr
  299. * @param string $keyField
  300. * @return mixed
  301. */
  302. public static function mergeArrayWithKey($arr1,$arr2,$keyArr=[],$keyField='ID'){
  303. foreach ($arr1 as $key=>$value){
  304. $arr1[$key]=array_merge($arr1[$key],$arr2[$key]??[]);
  305. if($keyArr){
  306. $arr1[$key][$keyField] = $keyArr[$key]??'';
  307. }
  308. }
  309. return $arr1;
  310. }
  311. /**
  312. * 中文UTF8 转 gbk
  313. * @param $text
  314. * @return false|string|string[]|null
  315. */
  316. public static function textConvert($text) {
  317. if ($text==='') {
  318. return '';
  319. }
  320. if (preg_match('/\,/', $text)){
  321. $text = preg_replace('/\,/', '|', $text);
  322. }
  323. // 只有是中文时才需要转码
  324. if (!preg_match('/[\x{4e00}-\x{9fa5}]/u', $text)) {
  325. return $text;
  326. }
  327. return mb_convert_encoding($text, 'gbk', 'utf-8');
  328. }
  329. /**
  330. * 数组里面的中文字符串全部转为GBK
  331. * @param array $arr
  332. * @return array
  333. */
  334. public static function arrTextConvert(array $arr){
  335. foreach($arr as $key => $str){
  336. $arr[$key] = self::textConvert($str);
  337. }
  338. return $arr;
  339. }
  340. /**
  341. * 获取目录内的所有文件
  342. * @param $dirPath
  343. * @return array
  344. */
  345. public static function dirFiles($dirPath){
  346. $files = [];
  347. //检测是否存在文件
  348. if (is_dir($dirPath)) {
  349. //打开目录
  350. if ($handle = opendir($dirPath)) {
  351. //返回当前文件的条目
  352. while (($file = readdir($handle)) !== false) {
  353. //去除特殊目录
  354. if ($file != "." && $file != "..") {
  355. //判断子目录是否还存在子目录
  356. if (!is_dir($dirPath . "/" . $file)) {
  357. $files[] = $dirPath . "/" . $file;
  358. } else {
  359. $files[$file] = self::dirFiles($dirPath . "/" . $file);
  360. }
  361. }
  362. }
  363. //关闭文件夹
  364. closedir($handle);
  365. }
  366. }
  367. //返回文件夹内文件的数组
  368. return $files;
  369. }
  370. /**
  371. * 获取审核状态tag颜色
  372. * @param $val
  373. * @return string
  374. */
  375. public static function statusType($val) {
  376. switch ($val) {
  377. case '0':
  378. return 'info';
  379. break;
  380. case '1':
  381. return 'success';
  382. break;
  383. case '2':
  384. return 'warning';
  385. break;
  386. case '3':
  387. return 'danger';
  388. break;
  389. default:
  390. return '';
  391. }
  392. }
  393. /**
  394. * 格式化筛选
  395. * @param $selData
  396. * @param $id
  397. * @param $name
  398. * @return array
  399. */
  400. public static function formatFilter($selData, $id, $name) {
  401. $arr=[];
  402. foreach ($selData as $key=>$value){
  403. $arr[$key]['id']=$value[$id];
  404. $arr[$key]['name']=$value[$name];
  405. }
  406. return $arr;
  407. }
  408. /**
  409. * 随机字符串
  410. * @param int $length
  411. * @param string $prefix
  412. * @param string $type
  413. * @return string
  414. */
  415. public static function randomString($length = 10, $prefix = '', $type = 'digit') {
  416. if ($type == 'digit') {
  417. $chars = "0123456789";
  418. } else {
  419. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  420. }
  421. if ($length - strlen($prefix) < 1) {
  422. return false;
  423. }
  424. $random_string = '';
  425. for ($i = 0; $i < $length - strlen($prefix); $i++) {
  426. $random_string .= $chars [mt_rand(0, strlen($chars) - 1)];
  427. }
  428. return $prefix.$random_string;
  429. }
  430. /**
  431. * 生成UUID
  432. * @param $upper boolean 是否大写
  433. * @param $symbol string 替换符号
  434. * @return string|string[]
  435. */
  436. public static function generateId(bool $upper = true, string $symbol = '')
  437. {
  438. $uuid = !$upper ? Uuid::uuid() : strtoupper(Uuid::uuid());
  439. return str_replace('-', $symbol, $uuid);
  440. }
  441. /**
  442. * 预警日志入库
  443. * @param $call
  444. * @return void
  445. */
  446. public static function alarmCall($call)
  447. {
  448. try {
  449. $model = new AlarmCall();
  450. $model->trace_id = $call['trace-id'];
  451. $model->content = $call;
  452. $model->insert();
  453. } catch (\yii\mongodb\Exception $e) {
  454. LoggerTool::error($call);
  455. LoggerTool::error(sprintf('[%s] [%s] [%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
  456. } catch (\Exception $e) {
  457. }
  458. }
  459. }