Tool.php 12 KB

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