-
Notifications
You must be signed in to change notification settings - Fork 7
/
Client.php
103 lines (90 loc) · 2.8 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
declare(strict_types=1);
namespace Yurun\TDEngine;
use InvalidArgumentException;
use Yurun\TDEngine\Action\Sql\SqlResult;
use Yurun\TDEngine\Constants\TimeStampFormat;
use Yurun\TDEngine\Exception\NetworkException;
use Yurun\TDEngine\Exception\OperationException;
use Yurun\Util\HttpRequest;
use Yurun\Util\YurunHttp\Http\Psr7\Uri;
class Client
{
/**
* @var ClientConfig
*/
protected $config;
/**
* @var HttpRequest|null
*/
protected $httpClient;
public function __construct(ClientConfig $config)
{
$this->config = $config;
if ($config->getKeepAlive())
{
$this->httpClient = new HttpRequest();
}
}
public function getConfig(): ClientConfig
{
return $this->config;
}
public function buildUrl(string $path): string
{
$config = $this->getConfig();
return Uri::makeUri($config->getHost(), $path, '', $config->getPort(), $config->getSsl() ? 'https' : 'http', '', $config->getUser() . ':' . $config->getPassword())->__toString();
}
public function request(string $path, string $postBody): array
{
$config = $this->getConfig();
if ($config->getKeepAlive())
{
$httpClient = $this->httpClient;
}
else
{
$httpClient = new HttpRequest();
}
if ('' !== ($hostName = $config->getHostName()))
{
$httpClient->header('Host', $hostName);
}
$response = $httpClient->post($this->buildUrl($path), $postBody);
$result = $response->json(true);
if (null === $result || false === $result)
{
throw new NetworkException(sprintf('Http request failed! statusCode:%s, errno:%s, error:%s', $response->getStatusCode(), $response->getErrno(), $response->getError()));
}
if ('succ' !== $result['status'])
{
throw new OperationException($result['desc'], $result['code']);
}
return $result;
}
public function sql(string $sql): SqlResult
{
$config = $this->getConfig();
switch ($config->getTimestampFormat())
{
case TimeStampFormat::LOCAL_STRING:
$path = '/rest/sql';
break;
case TimeStampFormat::TIMESTAMP:
$path = '/rest/sqlt';
break;
case TimeStampFormat::UTC_STRING:
$path = '/rest/sqlutc';
break;
default:
throw new InvalidArgumentException(sprintf('Invalid timestampFormat %s', $config->getTimestampFormat()));
}
$db = $config->getDb();
if ('' !== $db)
{
$path .= '/' . $db;
}
$result = $this->request($path, $sql);
return new SqlResult($result);
}
}