-
Notifications
You must be signed in to change notification settings - Fork 972
/
Elasticsearch.php
289 lines (270 loc) · 9.63 KB
/
Elasticsearch.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
<?php
/**
* Elasticsearch PHP Client
*
* @link https://github.com/elastic/elasticsearch-php
* @copyright Copyright (c) Elasticsearch B.V (https://www.elastic.co)
* @license https://opensource.org/licenses/MIT MIT License
*
* Licensed to Elasticsearch B.V under one or more agreements.
* Elasticsearch B.V licenses this file to you under the MIT License.
* See the LICENSE file in the project root for more information.
*/
declare(strict_types = 1);
namespace Elastic\Elasticsearch\Response;
use ArrayAccess;
use DateTime;
use Elastic\Elasticsearch\Exception\ArrayAccessException;
use Elastic\Elasticsearch\Exception\ClientResponseException;
use Elastic\Elasticsearch\Exception\ServerResponseException;
use Elastic\Elasticsearch\Traits\MessageResponseTrait;
use Elastic\Elasticsearch\Traits\ProductCheckTrait;
use Elastic\Elasticsearch\Utility;
use Elastic\Transport\Exception\UnknownContentTypeException;
use Elastic\Transport\Serializer\CsvSerializer;
use Elastic\Transport\Serializer\JsonSerializer;
use Elastic\Transport\Serializer\NDJsonSerializer;
use Elastic\Transport\Serializer\XmlSerializer;
use Psr\Http\Message\ResponseInterface;
use stdClass;
/**
* Wraps a PSR-7 ResponseInterface offering helpers to deserialize the body response
*/
class Elasticsearch implements ElasticsearchInterface, ResponseInterface, ArrayAccess
{
const HEADER_CHECK = 'X-Elastic-Product';
const PRODUCT_NAME = 'Elasticsearch';
use ProductCheckTrait;
use MessageResponseTrait;
protected array $asArray;
protected object $asObject;
protected string $asString;
/**
* The PSR-7 response
*/
protected ResponseInterface $response;
/**
* Enable or disable the response Exception
*/
protected bool $responseException;
/**
* @throws ClientResponseException if status code 4xx
* @throws ServerResponseException if status code 5xx
*/
public function setResponse(ResponseInterface $response, bool $throwException = true): void
{
$this->productCheck($response);
$this->response = $response;
$status = $response->getStatusCode();
if ($throwException && $status > 399 && $status < 500) {
$error = new ClientResponseException(
sprintf("%s %s: %s", $status, $response->getReasonPhrase(), (string) $response->getBody()),
$status
);
throw $error->setResponse($response);
} elseif ($throwException && $status > 499 && $status < 600) {
$error = new ServerResponseException(
sprintf("%s %s: %s", $status, $response->getReasonPhrase(), (string) $response->getBody()),
$status
);
throw $error->setResponse($response);
}
}
/**
* Return true if status code is 2xx
*/
public function asBool(): bool
{
return $this->response->getStatusCode() >=200 && $this->response->getStatusCode() < 300;
}
/**
* Converts the body content to array, if possible.
* Otherwise, it throws an UnknownContentTypeException
* if Content-Type is not specified or unknown.
*
* @throws UnknownContentTypeException
*/
public function asArray(): array
{
if (isset($this->asArray)) {
return $this->asArray;
}
if (!$this->response->hasHeader('Content-Type')) {
throw new UnknownContentTypeException('No Content-Type specified in the response');
}
$contentType = $this->response->getHeaderLine('Content-Type');
if (strpos($contentType, 'application/json') !== false ||
strpos($contentType, 'application/vnd.elasticsearch+json') !== false) {
$this->asArray = JsonSerializer::unserialize($this->asString());
return $this->asArray;
}
if (strpos($contentType, 'application/x-ndjson') !== false ||
strpos($contentType, 'application/vnd.elasticsearch+x-ndjson') !== false) {
$this->asArray = NDJsonSerializer::unserialize($this->asString());
return $this->asArray;
}
if (strpos($contentType, 'text/csv') !== false) {
$this->asArray = CsvSerializer::unserialize($this->asString());
return $this->asArray;
}
throw new UnknownContentTypeException(sprintf(
"Cannot deserialize the reponse as array with Content-Type: %s",
$contentType
));
}
/**
* Converts the body content to object, if possible.
* Otherwise, it throws an UnknownContentTypeException
* if Content-Type is not specified or unknown.
*
* @throws UnknownContentTypeException
*/
public function asObject(): object
{
if (isset($this->asObject)) {
return $this->asObject;
}
$contentType = $this->response->getHeaderLine('Content-Type');
if (strpos($contentType, 'application/json') !== false ||
strpos($contentType, 'application/vnd.elasticsearch+json') !== false) {
$this->asObject = JsonSerializer::unserialize($this->asString(), ['type' => 'object']);
return $this->asObject;
}
if (strpos($contentType, 'application/x-ndjson') !== false ||
strpos($contentType, 'application/vnd.elasticsearch+x-ndjson') !== false) {
$this->asObject = NDJsonSerializer::unserialize($this->asString(), ['type' => 'object']);
return $this->asObject;
}
if (strpos($contentType, 'text/xml') !== false || strpos($contentType, 'application/xml') !== false) {
$this->asObject = XmlSerializer::unserialize($this->asString());
return $this->asObject;
}
throw new UnknownContentTypeException(sprintf(
"Cannot deserialize the reponse as object with Content-Type: %s",
$contentType
));
}
/**
* Converts the body content to string
*/
public function asString(): string
{
if (empty($this->asString)) {
$this->asString = (string) $this->response->getBody();
}
return $this->asString;
}
/**
* Converts the body content to string
*/
public function __toString(): string
{
return $this->asString();
}
/**
* Access the body content as object properties
*
* @see https://www.php.net/manual/en/language.oop5.overloading.php#object.get
*/
public function __get($name)
{
return $this->asObject()->$name ?? null;
}
/**
* ArrayAccess interface
*
* @see https://www.php.net/manual/en/class.arrayaccess.php
*/
public function offsetExists($offset): bool
{
return isset($this->asArray()[$offset]);
}
/**
* ArrayAccess interface
*
* @see https://www.php.net/manual/en/class.arrayaccess.php
*
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->asArray()[$offset];
}
/**
* ArrayAccess interface
*
* @see https://www.php.net/manual/en/class.arrayaccess.php
*/
public function offsetSet($offset, $value): void
{
throw new ArrayAccessException('The array is reading only');
}
/**
* ArrayAccess interface
*
* @see https://www.php.net/manual/en/class.arrayaccess.php
*/
public function offsetUnset($offset): void
{
throw new ArrayAccessException('The array is reading only');
}
/**
* Map the response body to an object of a specific class
* by default the class is the PHP standard one (stdClass)
*
* This mapping works only for ES|QL results (with columns and values)
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/esql.html
*
* @return object[]
*/
public function mapTo(string $class = stdClass::class): array
{
$response = $this->asArray();
if (!isset($response['columns']) || !isset($response['values'])) {
throw new UnknownContentTypeException(sprintf(
"The response is not a valid ES|QL result. I cannot mapTo(\"%s\")",
$class
));
}
$iterator = [];
$ncol = count($response['columns']);
foreach ($response['values'] as $value) {
$obj = new $class;
for ($i=0; $i < $ncol; $i++) {
$field = Utility::formatVariableName($response['columns'][$i]['name']);
if ($class !== stdClass::class && !property_exists($obj, $field)) {
continue;
}
switch($response['columns'][$i]['type']) {
case 'boolean':
$obj->{$field} = (bool) $value[$i];
break;
case 'date':
$obj->{$field} = new DateTime($value[$i]);
break;
case 'alias':
case 'text':
case 'keyword':
case 'ip':
$obj->{$field} = (string) $value[$i];
break;
case 'integer':
$obj->{$field} = (int) $value[$i];
break;
case 'long':
case 'double':
$obj->{$field} = (float) $value[$i];
break;
case 'null':
$obj->{$field} = null;
break;
default:
$obj->{$field} = $value[$i];
}
}
$iterator[] = $obj;
}
return $iterator;
}
}