Tool.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 $dir
  241. * @throws Exception
  242. */
  243. public static function clearDir($dir){
  244. $dirHandle = opendir( $dir );
  245. if($dirHandle === false){
  246. throw new Exception('打开目录失败');
  247. }
  248. while( ($file = readdir( $dirHandle )) !== false ){
  249. if ( $file != '.' && $file != '..' && $file != '.gitignore' ) {
  250. unlink( $dir . '/' . $file );
  251. }
  252. }
  253. }
  254. /**
  255. * 过滤特殊字符
  256. * @param $strParam
  257. * @return string|string[]|null
  258. */
  259. public static function filterSpecialChar($strParam){
  260. $regex = "/\/|\~|\,|\。|\!|\?|\“|\”|\【|\】|\『|\』|\:|\;|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
  261. return preg_replace($regex,"",$strParam);
  262. }
  263. public static function allow_area($area, $search) {
  264. $result = false;
  265. foreach ($search as $key => $value) {
  266. $count = count($value);
  267. //不够三项的,补充到三项
  268. if ($count < 3) {
  269. $num = 3 - $count;
  270. $value += array_fill($count, $num, '');
  271. }
  272. if ($value[0] == '') { //说明地区选的全部
  273. $result = true;
  274. break;
  275. }
  276. if ($value[0] == $area[0] && ($value[1] == '' || $value[1] == $area[1]) && ($value[2] == '' || $value[2] == $area[2])) {
  277. $result = true;
  278. break;
  279. }
  280. }
  281. return $result;
  282. }
  283. /**
  284. * 转驼峰
  285. * @param $words
  286. * @param string $separator
  287. * @return string
  288. */
  289. public static function toCamelize( $words , $separator = '_') {
  290. if(!$words){
  291. return '';
  292. }
  293. $words = $separator. str_replace($separator, " ", strtolower($words));
  294. return ltrim(str_replace(" ", "", ucwords($words)), $separator );
  295. }
  296. public static function isConsoleApp(){
  297. return (\Yii::$app->id == 'app-console');
  298. }
  299. /**
  300. * 根据KEY合并两个数组
  301. * @param $arr1
  302. * @param $arr2
  303. * @param array $keyArr
  304. * @param string $keyField
  305. * @return mixed
  306. */
  307. public static function mergeArrayWithKey($arr1,$arr2,$keyArr=[],$keyField='ID'){
  308. foreach ($arr1 as $key=>$value){
  309. $arr1[$key]=array_merge($arr1[$key],$arr2[$key]??[]);
  310. if($keyArr){
  311. $arr1[$key][$keyField] = $keyArr[$key]??'';
  312. }
  313. }
  314. return $arr1;
  315. }
  316. /**
  317. * 中文UTF8 转 gbk
  318. * @param $text
  319. * @return false|string|string[]|null
  320. */
  321. public static function textConvert($text) {
  322. if ($text==='') {
  323. return '';
  324. }
  325. if (preg_match('/\,/', $text)){
  326. $text = preg_replace('/\,/', '|', $text);
  327. }
  328. // 只有是中文时才需要转码
  329. if (!preg_match('/[\x{4e00}-\x{9fa5}]/u', $text)) {
  330. return $text;
  331. }
  332. return mb_convert_encoding($text, 'gbk', 'utf-8');
  333. }
  334. /**
  335. * 数组里面的中文字符串全部转为GBK
  336. * @param array $arr
  337. * @return array
  338. */
  339. public static function arrTextConvert(array $arr){
  340. foreach($arr as $key => $str){
  341. $arr[$key] = self::textConvert($str);
  342. }
  343. return $arr;
  344. }
  345. /**
  346. * 获取目录内的所有文件
  347. * @param $dirPath
  348. * @return array
  349. */
  350. public static function dirFiles($dirPath){
  351. $files = [];
  352. //检测是否存在文件
  353. if (is_dir($dirPath)) {
  354. //打开目录
  355. if ($handle = opendir($dirPath)) {
  356. //返回当前文件的条目
  357. while (($file = readdir($handle)) !== false) {
  358. //去除特殊目录
  359. if ($file != "." && $file != "..") {
  360. //判断子目录是否还存在子目录
  361. if (!is_dir($dirPath . "/" . $file)) {
  362. $files[] = $dirPath . "/" . $file;
  363. } else {
  364. $files[$file] = self::dirFiles($dirPath . "/" . $file);
  365. }
  366. }
  367. }
  368. //关闭文件夹
  369. closedir($handle);
  370. }
  371. }
  372. //返回文件夹内文件的数组
  373. return $files;
  374. }
  375. /**
  376. * 获取审核状态tag颜色
  377. * @param $val
  378. * @return string
  379. */
  380. public static function statusType($val) {
  381. switch ($val) {
  382. case '0':
  383. return 'info';
  384. break;
  385. case '1':
  386. return 'success';
  387. break;
  388. case '2':
  389. return 'warning';
  390. break;
  391. case '3':
  392. return 'danger';
  393. break;
  394. default:
  395. return '';
  396. }
  397. }
  398. /**
  399. * 格式化筛选
  400. * @param $selData
  401. * @param $id
  402. * @param $name
  403. * @return array
  404. */
  405. public static function formatFilter($selData, $id, $name) {
  406. $arr=[];
  407. foreach ($selData as $key=>$value){
  408. $arr[$key]['id']=$value[$id];
  409. $arr[$key]['name']=$value[$name];
  410. }
  411. return $arr;
  412. }
  413. /**
  414. * 随机字符串
  415. * @param int $length
  416. * @param string $prefix
  417. * @param string $type
  418. * @return string
  419. */
  420. public static function randomString($length = 10, $prefix = '', $type = 'digit') {
  421. if ($type == 'digit') {
  422. $chars = "0123456789";
  423. } else {
  424. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  425. }
  426. if ($length - strlen($prefix) < 1) {
  427. return false;
  428. }
  429. $random_string = '';
  430. for ($i = 0; $i < $length - strlen($prefix); $i++) {
  431. $random_string .= $chars [mt_rand(0, strlen($chars) - 1)];
  432. }
  433. return $prefix.$random_string;
  434. }
  435. /**
  436. * 生成UUID
  437. * @param $upper boolean 是否大写
  438. * @param $symbol string 替换符号
  439. * @return string|string[]
  440. */
  441. public static function generateId(bool $upper = true, string $symbol = '')
  442. {
  443. $uuid = !$upper ? Uuid::uuid() : strtoupper(Uuid::uuid());
  444. return str_replace('-', $symbol, $uuid);
  445. }
  446. /**
  447. * 预警日志入库
  448. * @param $call
  449. * @return void
  450. * @throws \Exception
  451. */
  452. public static function alarmCall($call)
  453. {
  454. try {
  455. $model = new AlarmCall();
  456. $model->brand = $call['brand'];
  457. $model->stance = $call['stance'];
  458. $model->trace_id = $call['trace-id'];
  459. $model->content = $call;
  460. $model->insert();
  461. } catch (\yii\mongodb\Exception $e) {
  462. LoggerTool::error($call);
  463. LoggerTool::error(sprintf('[%s] [%s] [%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
  464. }
  465. }
  466. /* iPay88订单写入MongoDB.
  467. * @param $call
  468. * @return void
  469. * @throws \Exception
  470. */
  471. public static function approachOrderCall($call)
  472. {
  473. try {
  474. $model = new ApproachOrderCall();
  475. $model->sn = $call['RefNo'];
  476. $model->TransId = $call['TransId'];
  477. $model->Signature = $call['Signature'];
  478. $model->data = $call;
  479. $model->insert();
  480. } catch (\yii\mongodb\Exception $e) {
  481. LoggerTool::info($call);
  482. LoggerTool::error(sprintf('[%s] [%s] [%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
  483. }
  484. }
  485. /**
  486. * 订单推送wst系统回执写入mongo.
  487. * @param $call
  488. * @return void
  489. * @throws \Exception
  490. */
  491. public static function wstOrderCall($call)
  492. {
  493. try {
  494. $model = new WstOrderCall();
  495. $model->order_id = $call['order_id'];
  496. $model->order_no = $call['order_no'];
  497. $model->warehouse_id = $call['warehouse_id'];
  498. $model->delivery_method_name = $call['warehouse_id'];
  499. $model->addon_service_name = $call['addon_service_name'];
  500. $model->country = $call['country'];
  501. $model->state = $call['state'];
  502. $model->city = $call['city'];
  503. $model->post_code = $call['post_code'];
  504. $model->address = $call['address'];
  505. $model->consignee = $call['consignee'];
  506. $model->telephone = $call['telephone'];
  507. $model->comment = $call['comment'];
  508. $model->products = $call['products'];
  509. $model->insert();
  510. } catch (\yii\mongodb\Exception $e) {
  511. LoggerTool::info($call);
  512. LoggerTool::error(sprintf('[%s] [%s] [%s]', $e->getFile(), $e->getLine(), $e->getMessage()));
  513. }
  514. }
  515. /**
  516. * @throws AddressNotFoundException
  517. * @throws InvalidDatabaseException
  518. */
  519. public static function remoteAddrCall($remoteAddr): bool
  520. {
  521. // 是否有效的IP
  522. if (!filter_var($remoteAddr, FILTER_VALIDATE_IP)) {
  523. return false;
  524. }
  525. // 替换为 GeoLite2 数据库文件的实际路径
  526. $dbPath = \Yii::getAlias('@common/runtime/geoLite//GeoLite2-Country.mmdb');
  527. // 初始化 MaxMind 数据库读取器
  528. $reader = new Reader($dbPath);
  529. // 查询 IP 地址的地理位置
  530. $record = $reader->country($remoteAddr);
  531. // 返回国家名称
  532. $countryName = $record->country->name;
  533. if (!in_array($countryName, ['China', 'Malaysia'])) {
  534. return false;
  535. }
  536. return true;
  537. }
  538. public static function checkArrayElementSubstringOfString(string $string, array $array): bool
  539. {
  540. if (empty($string) || empty($array)) {
  541. return false;
  542. }
  543. foreach ($array as $substr) {
  544. if (strpos($string, $substr) !== false) {
  545. return true;
  546. }
  547. }
  548. return false;
  549. }
  550. }