Tool.php 18 KB

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