Tool.php 13 KB

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