Tool.php 17 KB

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