Tool.php 16 KB

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