Tool.php 13 KB

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