Tool.php 16 KB

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