Tool.php 13 KB

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