Tool.php 14 KB

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