Tool.php 13 KB

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