-
Notifications
You must be signed in to change notification settings - Fork 1
/
Client.php
79 lines (67 loc) · 2.67 KB
/
Client.php
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
77
78
79
<?php
declare(strict_types=1);
namespace Cocoyo\Nacos;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\TransferException;
use Cocoyo\Nacos\Exception\ClientException;
use Cocoyo\Nacos\Exception\ServerException;
use Hyperf\Contract\StdoutLoggerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
abstract class Client
{
const DEFAULT_URI = '127.0.0.1:8848';
/**
* Will execute this closure everytime when the nacos client send a HTTP request,
* and the closure should return a GuzzleHttp\ClientInterface instance.
* $clientFactory(array $options).
*
* @var \Closure
*/
private $clientFactory;
/**
* @var StdoutLoggerInterface
*/
private $logger;
public function __construct(\Closure $clientFactory, LoggerInterface $logger = null)
{
$this->clientFactory = $clientFactory;
$this->logger = $logger ?: new NullLogger();
}
protected function resolveOptions(array $options, array $availableOptions): array
{
// Add key of ACL token to $availableOptions
$availableOptions[] = 'token';
return array_intersect_key($options, array_flip($availableOptions));
}
/**
* Send a HTTP request.
*/
protected function request(string $method, string $url, array $options = []): NacosResponse
{
$this->logger->debug(sprintf('Nacos Request [%s] %s', strtoupper($method), $url));
try {
// Create a HTTP Client by $clientFactory closure.
$clientFactory = $this->clientFactory;
$client = $clientFactory($options);
if (! $client instanceof ClientInterface) {
throw new ClientException(sprintf('The client factory should create a %s instance.', ClientInterface::class));
}
$response = $client->request($method, $url, $options);
} catch (TransferException $e) {
$message = sprintf('Something went wrong when calling (%s).', $e->getMessage());
$this->logger->error($message);
throw new ServerException($e->getMessage(), $e->getCode(), $e);
}
if ($response->getStatusCode() >= 400) {
$message = sprintf('Something went wrong when calling nacos (%s - %s).', $response->getStatusCode(), $response->getReasonPhrase());
$this->logger->error($message);
$message .= PHP_EOL . (string) $response->getBody();
if ($response->getStatusCode() >= 500) {
throw new ServerException($message, $response->getStatusCode());
}
throw new ClientException($message, $response->getStatusCode());
}
return new NacosResponse($response);
}
}