forked from sergix44/gradio-client-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoteClient.php
More file actions
76 lines (58 loc) · 2.31 KB
/
RemoteClient.php
File metadata and controls
76 lines (58 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace SergiX44\Gradio\Client;
use GuzzleHttp\Client as Guzzle;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use SergiX44\Gradio\Event\EnhancedClient;
use SergiX44\Hydrator\Hydrator;
use SergiX44\Hydrator\HydratorInterface;
abstract class RemoteClient extends RegisterEvents
{
private string $src;
protected Guzzle $httpClient;
protected HydratorInterface $hydrator;
public function __construct(string $src, array $httpClientOptions = [])
{
if (
! str_starts_with($src, 'http://') &&
! str_starts_with($src, 'https://') &&
! str_starts_with($src, 'ws://') &&
! str_starts_with($src, 'wss://')
) {
throw new InvalidArgumentException('The src must not contain the protocol');
}
$this->src = str_ends_with($src, '/') ? $src : "{$src}/";
$this->hydrator = new Hydrator();
$this->httpClient = new Guzzle(array_merge([
'base_uri' => str_replace('ws', 'http', $this->src),
'headers' => [
'User-Agent' => 'gradio_client_php/1.0',
'Accept' => 'application/json',
],
], $httpClientOptions));
}
protected function http(string $method, string $uri, array $params = [], array $opt = [], ?string $dto = null)
{
$response = $this->httpRaw($method, $uri, $params, $opt);
return $this->decodeResponse($response, $dto);
}
protected function httpRaw(string $method, string $uri, array $params = [], array $opt = [])
{
$keyContent = $method === 'get' ? 'query' : 'json';
return $this->httpClient->request($method, $uri, array_merge([
$keyContent => $params,
], $opt));
}
protected function ws(string $uri, array $options = []): EnhancedClient
{
return new EnhancedClient(str_replace('http', 'ws', $this->src).$uri, $options);
}
protected function decodeResponse(ResponseInterface|string $response, ?string $mapTo = null): mixed
{
$body = $response instanceof ResponseInterface ? $response->getBody()->getContents() : $response;
if ($mapTo !== null) {
return $this->hydrator->hydrateWithJson($mapTo, $body);
}
return json_decode($body, true, flags: JSON_THROW_ON_ERROR);
}
}