Tool.php 12 KB

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