RestClient::requestQuery()   B
last analyzed

Complexity

Conditions 4
Paths 15

Size

Total Lines 33
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 25
nc 15
nop 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Ytake\KsqlClient;
5
6
use Fig\Http\Message\StatusCodeInterface;
7
use GuzzleHttp\Client as GuzzleClient;
8
use GuzzleHttp\ClientInterface;
9
use GuzzleHttp\Exception\ClientException;
10
use GuzzleHttp\Psr7\Request;
11
use GuzzleHttp\Psr7\Uri;
12
use GuzzleHttp\Psr7\UriNormalizer;
13
use Ytake\KsqlClient\Exception\KsqlRestClientException;
14
use Ytake\KsqlClient\Query\QueryInterface;
15
use Ytake\KsqlClient\Result\AbstractResult;
16
use Ytake\KsqlClient\Result\ErrorResult;
17
18
/**
19
 * Class RestClient
20
 */
21
class RestClient
22
{
23
    const USER_AGENT = 'PHP-KSQLClient';
24
25
    /** @var string */
26
    private $serverAddress;
27
28
    /** @var array<string, string> */
29
    private $properties = [];
30
31
    /** @var ClientInterface */
32
    private $client;
33
34
    /** @var bool */
35
    private $hasUserCredentials = false;
36
37
    /** @var AuthCredential */
38
    private $authCredential;
39
40
    /** @var array */
41
    private $options = [];
42
43
    /**
44
     * RestClient constructor.
45
     *
46
     * @param string               $serverAddress
47
     * @param array                $properties
48
     * @param ClientInterface|null $client
49
     */
50
    public function __construct(
51
        string $serverAddress,
52
        array $properties = [],
53
        ClientInterface $client = null
54
    ) {
55
        $this->serverAddress = $serverAddress;
56
        $this->properties = $properties;
57
        $this->client = (is_null($client)) ? $this->buildClient() : $client;
58
    }
59
60
    /**
61
     * build GuzzleHttp Client
62
     *
63
     * @return ClientInterface
64
     */
65
    protected function buildClient(): ClientInterface
66
    {
67
        return new GuzzleClient([
68
            'headers' => [
69
                'User-Agent' => self::USER_AGENT,
70
                'Accept'     => 'application/json',
71
            ],
72
        ]);
73
    }
74
75
    /**
76
     * @param AuthCredential $authCredential
77
     */
78
    public function setAuthCredentials(AuthCredential $authCredential): void
79
    {
80
        $this->authCredential = $authCredential;
81
        $this->hasUserCredentials = true;
82
    }
83
84
    /**
85
     * @return null|AuthCredential
86
     */
87
    public function getAuthCredentials(): ?AuthCredential
88
    {
89
        return $this->authCredential;
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    public function getServerAddress(): string
96
    {
97
        return $this->serverAddress;
98
    }
99
100
    /**
101
     * @param string $serverAddress
102
     */
103
    public function setServerAddress(string $serverAddress): void
104
    {
105
        $this->serverAddress = $serverAddress;
106
    }
107
108
    /**
109
     * @param QueryInterface $query
110
     * @param int            $timeout
111
     * @param bool           $debug
112
     *
113
     * @return AbstractResult|null
114
     * @throws \GuzzleHttp\Exception\GuzzleException
115
     */
116
    public function requestQuery(
117
        QueryInterface $query,
118
        int $timeout = 500000,
119
        bool $debug = false
120
    ): AbstractResult {
121
        $uri = new Uri($this->serverAddress);
122
        $uri = $uri->withPath($query->uri());
123
        $normalize = UriNormalizer::normalize(
124
            $uri,
125
            UriNormalizer::REMOVE_DUPLICATE_SLASHES
126
        );
127
        $request = new Request($query->httpMethod(), $normalize);
128
        try {
129
            $options = $this->getOptions($query, $timeout, $debug);
130
            if ($this->hasUserCredentials) {
131
                $credentials = $this->getAuthCredentials();
132
                $options = array_merge($options, [
133
                    'auth' => [$credentials->getUserName(), $credentials->getPassword()],
134
                ]);
135
            }
136
            $response = $this->client->send(
137
                $request,
138
                array_merge($options, $this->options)
139
            );
140
            if ($response->getStatusCode() == StatusCodeInterface::STATUS_OK) {
141
                return $query->queryResult($response);
142
            }
143
144
            return new ErrorResult($response);
145
        } catch (ClientException $e) {
146
            throw new KsqlRestClientException($e->getMessage(), $e->getCode(), $e);
147
        }
148
    }
149
150
    /**
151
     * @param QueryInterface $query
152
     * @param int            $timeout
153
     * @param bool           $debug
154
     *
155
     * @return array
156
     */
157
    protected function getOptions(
158
        QueryInterface $query,
159
        int $timeout = 500000,
160
        bool $debug = false
161
    ): array {
162
        return [
163
            'timeout' => $timeout,
164
            'body'    => json_encode($query->toArray()),
165
            'debug'   => $debug,
166
        ];
167
    }
168
169
    /**
170
     * @param array $options
171
     */
172
    public function setOptions(array $options): void
173
    {
174
        $this->options = $options;
175
    }
176
}
177