Tool.php 15 KB

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