goodsnotices/app/helpers/apiRequest.php

82 lines
2.2 KiB
PHP
Raw Normal View History

2024-05-25 14:06:58 +00:00
<?php
namespace App\helpers;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class apiRequest
{
public static Client|null $client=null;
public static function getClient(): Client
{
if (!self::$client) {
self::$client = new Client();
}
return self::$client;
}
/**
* @throws GuzzleException
*/
public static function request(string $url, mixed $param=[], FormType $type = FormType::urlencoded, bool $isJson = true, int $timeout = 5, array $extern = []):mixed
{
return self::requests(self::getClient(),$url,$param,$type,$isJson,$timeout,$extern);
}
/**
* json请求api
* @param Client $client
* @param string $url
* @param mixed $param
* @param FormType $type 1 x-www-form-urlencoded,2 json, 3 multipart/form-data 4 get query
* @param bool $isJson
* @param int $timeout
* @param int[] $extern
* @return mixed
* @throws GuzzleException
* @throws Exception
*/
public static function requests(Client $client,string $url, mixed $param=[], FormType $type = FormType::urlencoded, bool $isJson = true, int $timeout = 5, array $extern = []): mixed
{
$params = [
'timeout' => $timeout
];
switch ($type) {
case FormType::urlencoded:
$params['form_params'] = $param;
$type = 'POST';
break;
case FormType::json:
$params['json'] = $param;
$type = 'POST';
break;
case FormType::formData:
$params['multipart'] = $param;
$type = 'POST';
break;
default:
$params['query'] = $param;
$type = 'GET';
break;
}
if ($extern) {
$params = array_merge($params, $extern);
}
$r = $client->request($type, $url, $params);
$res = $r->getBody()->getContents();
if ($isJson) {
$data = json_decode($res, true);
if ($data === false) {
throw new Exception($res, 0);
}
} else {
$data = $res;
}
return $data;
}
}