Tool.php 15 KB

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