Tool.php 15 KB

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