123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- <?php
- namespace daorui;
- class DaoRuiBase
- {
-
- public function __construct()
- {
- }
-
- protected function getCache(string $field)
- {
- $cacheData = cache($field);
- if ($cacheData) {
-
- if (is_string($cacheData)) {
- $cacheData = json_decode($cacheData, true);
- }
- return $cacheData;
- }
- return [];
- }
-
- protected function setCache(array $data, string $field, $endTime)
- {
- cache($field, $data, ['expire' => $endTime]);
- }
-
- public function SendCurl(string $url, array $data = [], array $header = [], string $method = 'POST')
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-
- switch ($method) {
- case 'GET':
- if (!empty($data)) {
- $parsed_url = parse_url($url);
- if(isset($parsed_url['query'])){
- $url .= '&' . http_build_query($data);
- }else{
- $url .= '?' . http_build_query($data);
- }
- }
- break;
- case 'POST':
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
- break;
- default:
- throw new \Exception("不支持的请求方法");
- }
-
- $headerArr = [];
- foreach ($header as $key => $value) {
- $headerArr[] = $key . ': ' . $value;
- }
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
-
- curl_setopt($ch, CURLOPT_URL, $url);
-
- $response = curl_exec($ch);
-
- if (curl_errno($ch)) {
- throw new \Exception(curl_error($ch));
- }
- curl_close($ch);
- if (is_string($response)) {
- $response = json_decode($response, true);
- }
- Wlog('BaseDaoRui/SendCurl', [
- 'url' => $url,
- 'data' => $data,
- 'header' => $header,
- 'method' => $method,
- 'response' => $response,
- ]);
- return $response;
- }
- }
|