Tool.php 13 KB

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