Helper.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. use lwmf\base\Logger;
  3. class Helper
  4. {
  5. const PARAM_KEY_TYPE = [
  6. 'string' => 'string', // 字符串
  7. 'int' => 'int', // 数字
  8. 'float' => 'float', // float数字
  9. 'date' => 'date', // 日期
  10. 'datetime' => 'datetime', // 日期时间
  11. 'array_string' => 'array_string', // 包含字符串的数组
  12. 'array_float' => 'array_float', // 包含float的数组
  13. 'array_int' => 'array_int', // 包含int的数组
  14. ];
  15. /**
  16. * 检查字符串中是否含有任何一个子串
  17. * @param $str
  18. * @param array $arr
  19. * @param bool $case 是否区分大小写 0-否
  20. * @return bool
  21. */
  22. public static function hasAnyString($str, array $arr, bool $case = false): bool
  23. {
  24. foreach ($arr as $v) {
  25. if (!$case && stripos($str, $v) !== false) {
  26. return true;
  27. } elseif ($case && str_contains($str, $v)) {
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. /**
  34. * 获取图片完整路径
  35. * @param $imageUrl
  36. * @param string $default
  37. *
  38. * @return string
  39. * @author lizhi <1458705589@qq.com>
  40. * @date 2021/5/11
  41. */
  42. public static function getImageUrl($imageUrl, string $default = '', $isSmall = false): string
  43. {
  44. if (empty($imageUrl)) {
  45. return $default;
  46. }
  47. if (str_contains($imageUrl, 'http')) {
  48. return $imageUrl;
  49. }
  50. $imageUrl = IMAGEDOMAIN . '/' . ltrim($imageUrl, '/');
  51. if ($isSmall) {
  52. // 把后端用到图片的地方,加个后缀,类似!max200 !width600这种
  53. $imageUrl .= '!max200';
  54. }
  55. return $imageUrl;
  56. }
  57. /**
  58. * 格式化处理 imgs 字段
  59. * @param string|null $data
  60. * @param string $separator
  61. * @return array
  62. */
  63. public static function formatImgsFiled(?string $data, string $separator = ',', $isSmall = false): array
  64. {
  65. if (!$data) {
  66. return [];
  67. }
  68. $data = array_filter(explode($separator, $data));
  69. return array_map(function ($img) use ($isSmall) {
  70. return Helper::getImageUrl($img, '', $isSmall);
  71. }, $data);
  72. }
  73. public static function time_tran($time)
  74. {
  75. $text = '请选择正确的时间!';
  76. if(!$time){
  77. return $text;
  78. }
  79. $current = time();
  80. $t = $current - $time;
  81. $retArr = array('刚刚','秒前','分钟前','小时前','天前','月前','年前');
  82. switch($t){
  83. case $t < 0://时间大于当前时间,返回格式化时间
  84. $text = date('Y-m-d',$time);
  85. break;
  86. case $t == 0://刚刚
  87. $text = $retArr[0];
  88. break;
  89. case $t < 60:// 几秒前
  90. $text = $t.$retArr[1];
  91. break;
  92. case $t < 3600://几分钟前
  93. $text = floor($t / 60).$retArr[2];
  94. break;
  95. case $t < 86400://几小时前
  96. $text = floor($t / 3600).$retArr[3];
  97. break;
  98. case $t < 2592000: //几天前
  99. $text = floor($t / 86400).$retArr[4];
  100. break;
  101. case $t < 31536000: //几个月前
  102. $text = floor($t / 2592000).$retArr[5];
  103. break;
  104. default : //几年前
  105. $text = floor($t / 31536000).$retArr[6];
  106. }
  107. return $text;
  108. }
  109. /**
  110. * 检查数组是否指定键都存在 true-都在
  111. * - checkEmptyKey(['num' => 1], ['num']) => true
  112. * - checkEmptyKey(['num' => 1], ['id']) => false
  113. * - checkEmptyKey(['num' => 0], ['num']) => false
  114. * - checkEmptyKey(['num' => 0], ['num'], ['num') => true
  115. *
  116. * @param array $data
  117. * @param $keys
  118. * @param array $allowEmpty 允许为空的字段
  119. *
  120. * @return bool true-通过检查
  121. * @author lizhi <1458705589@qq.com>
  122. * @date 2021/6/18
  123. */
  124. public static function checkEmptyKey($data, $keys, array $allowEmpty = [])
  125. {
  126. if (is_array($keys)) {
  127. foreach ($keys as $item) {
  128. if (!isset($data[$item]) || (!in_array($item, $allowEmpty) && empty($data[$item]))) {
  129. return false;
  130. }
  131. }
  132. } elseif (!isset($data[$keys]) || (!in_array($keys, $allowEmpty) && empty($data[$keys]))) {
  133. return false;
  134. }
  135. return true;
  136. }
  137. public static function getPostString($key, $default = null)
  138. {
  139. return self::getArrParam($_POST, $key, 'string', $default);
  140. }
  141. public static function getPostFloat($key, $default = null)
  142. {
  143. return self::getArrParam($_POST, $key, 'float', $default);
  144. }
  145. public static function getGetFloat($key, $default = null)
  146. {
  147. return self::getArrParam($_GET, $key, 'float', $default);
  148. }
  149. public static function isPhone(?string $phone)
  150. {
  151. return $phone && preg_match('/^1[3456789]\d{9}$/', $phone);
  152. }
  153. public static function getPostInt($key, $default = 0)
  154. {
  155. return self::getArrParam($_POST, $key, 'int', $default);
  156. }
  157. public static function getGetString($key, $default = null)
  158. {
  159. return self::getArrParam($_GET, $key, 'string', $default);
  160. }
  161. public static function getGetDate($key, $default = null)
  162. {
  163. return self::getArrParam($_GET, $key, 'date', $default);
  164. }
  165. public static function getPostDatetime($key, $default = null)
  166. {
  167. return self::getArrParam($_POST, $key, 'datetime', $default);
  168. }
  169. public static function getGetDatetime($key, $default = null)
  170. {
  171. return self::getArrParam($_GET, $key, 'datetime', $default);
  172. }
  173. public static function getPostDate($key, $default = null)
  174. {
  175. return self::getArrParam($_POST, $key, 'date', $default);
  176. }
  177. public static function getGetInt($key, $default = 0)
  178. {
  179. return self::getArrParam($_GET, $key, 'int', $default);
  180. }
  181. /**
  182. * 从数组中获取字段
  183. */
  184. public static function getArrParam($arr, $name, $type = 'string', $default = null)
  185. {
  186. if (isset($arr[$name])) {
  187. $param = $arr[$name];
  188. return self::formatByType($param, $type, $default);
  189. }
  190. return $default;
  191. }
  192. /**
  193. * @param string $name 从数组中获取字段,并进行安全处理 多维数组示例 area.name
  194. * @see self::formatByType()
  195. */
  196. public static function getByKey($arr, $name, $type = '', $default = null)
  197. {
  198. $nameArr = array_filter(explode('.', $name));
  199. if (count($nameArr) == 1) {
  200. if (!isset($arr[$name])) {
  201. return $default;
  202. } else {
  203. $param = $arr[$name];
  204. }
  205. } else if (count($nameArr) == 2) {
  206. if (!isset($arr[$nameArr[0]][$nameArr[1]])) {
  207. return $default;
  208. } else {
  209. $param = $arr[$nameArr[0]][$nameArr[1]];
  210. }
  211. } else {
  212. return $default;
  213. }
  214. return self::formatByType($param, $type, $default);
  215. }
  216. /**
  217. * 格式化数据
  218. * @param mixed $param
  219. * @param string $type 数据类型,将元素处理成这样的数据类型
  220. - string 字符串
  221. - int 数字
  222. - float float数字
  223. - date 日期
  224. - datetime 日期时间
  225. - array_string 包含字符串的数组
  226. - array_float 包含float的数组
  227. - array_int 包含int的数组
  228. * @param mixed $default
  229. * @return mixed
  230. */
  231. public static function formatByType($param, $type, $default)
  232. {
  233. if ($type == 'string') {
  234. $param = addslashes(trim($param));
  235. }
  236. elseif ($type == 'int') {
  237. $param = intval($param);
  238. }
  239. elseif ($type == 'float') {
  240. $param = floatval($param);
  241. }
  242. elseif ($type == 'date') {
  243. if (!empty($param)) {
  244. $param = date('Y-m-d', strtotime($param));
  245. } else {
  246. $param = $default;
  247. }
  248. }
  249. elseif ($type == 'datetime') {
  250. if (!empty($param)) {
  251. $param = date('Y-m-d H:i:s', strtotime($param));
  252. } else {
  253. $param = $default;
  254. }
  255. }
  256. elseif ($type == 'array_string') {
  257. if (!empty($param)) {
  258. foreach ($param as $key => &$item) {
  259. $item = addslashes(trim($item));
  260. }
  261. }
  262. }
  263. elseif ($type == 'array_float') {
  264. if (!empty($param)) {
  265. foreach ($param as $key => &$item) {
  266. $item = floatval($item);
  267. }
  268. }
  269. }
  270. elseif ($type == 'array_int') {
  271. if (!empty($param)) {
  272. foreach ($param as $key => &$item) {
  273. $item = intval($item);
  274. }
  275. }
  276. }
  277. return $param;
  278. }
  279. /**
  280. * 获取date格式的日期间隔
  281. */
  282. public static function intervalDays($date1, $date2)
  283. {
  284. $d = @(strtotime($date2) - strtotime($date1)) / (3600 * 24);
  285. return $d;
  286. }
  287. /**
  288. * 获取一个对象中的某个字段,返回数组
  289. * @param array $arr 通过查询返回的数组
  290. * @param string $column 字段名
  291. */
  292. public static function getObjectColumn(array $arr, $column = 'id')
  293. {
  294. $ret = [];
  295. if (!empty($arr)) {
  296. foreach ($arr as $key => $item) {
  297. $attributes = $item->attributes;
  298. isset($attributes[$column]) && $ret[] = $attributes[$column];
  299. }
  300. }
  301. return $ret;
  302. }
  303. public static function concatArray($arr1, $arr2)
  304. {
  305. foreach ($arr2 as $item) {
  306. if (!in_array($item, $arr1)) {
  307. $arr1[] = $item;
  308. }
  309. }
  310. return $arr1;
  311. }
  312. public static function toJson($code = 200, $data = [], $msg = '请求成功')
  313. {
  314. @header("Content-Type: text/json; charset=UTF-8");
  315. echo json_encode([
  316. 'code' => $code,
  317. 'msg' => $msg,
  318. 'data' => $data
  319. ]);
  320. \Yii::app()->end();
  321. }
  322. public static function error($msg, $code = 400, $data = [])
  323. {
  324. self::toJson($code, $data, $msg);
  325. }
  326. public static function ok($data = [], $msg = '操作成功', $code = 200)
  327. {
  328. self::toJson($code, $data, $msg);
  329. }
  330. public static function success($data = [], $msg = '操作成功', $code = 200)
  331. {
  332. self::toJson($code, $data, $msg);
  333. }
  334. public static function commonError($_msg = '', $_code = 500, $_data = [])
  335. {
  336. return self::commonReturn($_data, $_msg, $_code);
  337. }
  338. public static function commonReturn($_data = [], $_msg = '', $_code = 200)
  339. {
  340. return [
  341. 'code' => $_code,
  342. 'msg' => $_msg,
  343. 'data' => $_data
  344. ];
  345. }
  346. public static function dealCommonResult($res, $exit = true)
  347. {
  348. if ($exit || $res['code'] != 200) {
  349. Helper::toJson($res['code'], $res['data'], $res['msg']);
  350. }
  351. }
  352. public static function getRandomString($length = 20)
  353. {
  354. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  355. $str = "";
  356. for ($i = 0; $i < $length; $i++) {
  357. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  358. }
  359. return $str;
  360. }
  361. public static function getSign($data)
  362. {
  363. return md5($data . "145709480B89EE59E3F4D43A56C355F2");
  364. }
  365. /**
  366. * 将二维数组转化为对象数组
  367. * @param array $arr
  368. * @return array
  369. */
  370. public static function arrayToObjects(array $arr)
  371. {
  372. $ret = [];
  373. foreach ($arr as $item) {
  374. $ret[] = (object)$item;
  375. }
  376. return $ret;
  377. }
  378. /**
  379. * 异步批量get请求
  380. *
  381. * @param array $nodes 格式: 'key' => ['url', 'data'] key是标识key,url是请求host,data是post传递的数据
  382. * @param integer $timeOut 超时时间
  383. * @return void
  384. */
  385. public static function multiGet($nodes, $options = [] ,$timeOut = 5)
  386. {
  387. $mh = curl_multi_init();
  388. $curl_arr = [];
  389. // 将请求放入curl中
  390. foreach ($nodes as $key => $node) {
  391. if (!is_array($node)) {
  392. continue;
  393. }
  394. $ch = curl_init();
  395. $url = $node['url'] . (strpos($node['url'], '?') === FALSE ? '?' : '');
  396. if (isset($node['data'])) {
  397. $url .= http_build_query($node['data']);
  398. }
  399. curl_setopt($ch, CURLOPT_URL, $url);
  400. // 其他的参数按照 function GET($url, $get = array(), array $options = array()) 来
  401. curl_setopt($ch, CURLOPT_HEADER, 0);
  402. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
  403. curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  404. curl_setopt($ch, CURLOPT_SSLVERSION, 1);
  405. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  406. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  407. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  408. // 超时时间
  409. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
  410. foreach ($options as $k => $v) {
  411. curl_setopt($ch, $k, $v);
  412. }
  413. $curl_arr[$key] = $ch;
  414. curl_multi_add_handle($mh, $curl_arr[$key]);
  415. }
  416. // 发送请求
  417. $running = null;
  418. do {
  419. usleep(10000);
  420. curl_multi_exec($mh, $running);
  421. } while ($running > 0);
  422. // 获取请求数据,并删除请求
  423. $ret = [];
  424. foreach ($nodes as $key => $node) {
  425. $ret[$key] = curl_multi_getcontent($curl_arr[$key]);
  426. curl_multi_remove_handle($mh, $curl_arr[$key]);
  427. }
  428. curl_multi_close($mh);
  429. return $ret;
  430. }
  431. /**
  432. * array_column 一样用法
  433. */
  434. public static function arrayColumn($array, $column_key, $index_key = null): array
  435. {
  436. return $array && $array['records'] ? array_column($array['records'], $column_key, $index_key) : [];
  437. }
  438. /**
  439. * @param int $ipNum 每日ip次数限制
  440. * @param string $phone 手机号
  441. * @param int $phoneNum 每日单个手机号次数限制
  442. * @return array
  443. */
  444. public static function limitSmsSend(int $ipNum = 10, string $phone = '', int $phoneNum = 3):array
  445. {
  446. if ($ipNum > 0) {
  447. $ip = self::getUserHostIp();
  448. $key = 'limit_ip:' . date('Ymd') . '_' . $ip;
  449. if (RedisInstance::getInstance()->incr($key, 1, 86400) > $ipNum) {
  450. return Helper::commonError('今日短信次数超过限制i');
  451. }
  452. }
  453. if ($phone && $phoneNum > 0) {
  454. $key = 'limit_phone:' . date('Ymd') . '_' . $phone;
  455. if (RedisInstance::getInstance()->incr($key, 1, 86400) > $phoneNum) {
  456. return Helper::commonError('今日短信次数超过限制p');
  457. }
  458. }
  459. return Helper::commonReturn();
  460. }
  461. /**
  462. * 获取代理模式用户真实访问IP
  463. * 获取阿里云用户真实访问IP
  464. */
  465. public static function getUserHostIp()
  466. {
  467. if (isset($_SERVER['HTTP_X_ORIGINAL_FORWARDED_FOR']))
  468. {
  469. $ips = isset($_SERVER["HTTP_X_ORIGINAL_FORWARDED_FOR"]) ? explode(',', $_SERVER["HTTP_X_ORIGINAL_FORWARDED_FOR"]) : '';
  470. }
  471. else
  472. {
  473. $ips = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? explode(',', $_SERVER["HTTP_X_FORWARDED_FOR"]) : '';
  474. }
  475. if (isset($ips[0]))
  476. {
  477. $ip = $ips[0];
  478. }
  479. else
  480. {
  481. $ip = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : '';
  482. }
  483. return $ip ? $ip : '127.0.0.1';
  484. }
  485. public static function imageUpload($imagepath, $uploadpath)
  486. {
  487. try {
  488. $cosClient = new \Qcloud\Cos\Client(
  489. array(
  490. 'region' => 'ap-shanghai',
  491. // 'scheme' => 'https', //协议头部,默认为 http
  492. 'credentials'=> array(
  493. 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
  494. 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
  495. )
  496. )
  497. );
  498. $file = fopen($imagepath, "rb");
  499. if (!$file) {
  500. throw new Exception("读取图片失败");
  501. }
  502. $cosClient->putObject(['Bucket' => 'lewaimai-image-1251685925', 'Key' => $uploadpath, 'Body' => $file]);
  503. return Helper::commonReturn();
  504. } catch(Exception $e) {
  505. return Helper::commonError($e->getMessage());
  506. }
  507. }
  508. public static function imageDelete($path)
  509. {
  510. try {
  511. $cosClient = new \Qcloud\Cos\Client(
  512. array(
  513. 'region' => 'ap-shanghai',
  514. // 'scheme' => 'https', //协议头部,默认为 http
  515. 'credentials'=> array(
  516. 'secretId' => 'AKIDviIeLyQluythLAykSJ6oXH91upgR6iT8' ,
  517. 'secretKey' => 'tobSCsOn7yc6ToBSWegaM9rVGyiR6f95'
  518. )
  519. )
  520. );
  521. $cosClient->deleteObject(['Bucket' => 'lewaimai-image-1251685925', 'Key' => $path]);
  522. return Helper::commonReturn();
  523. } catch(Exception $e) {
  524. return Helper::commonError($e->getMessage());
  525. }
  526. }
  527. }