Tool.php 17 KB

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