|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of Solr Client Symfony package. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) ingatlan.com Zrt. <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* This source file is subject to the MIT license that is bundled |
|
11
|
|
|
* with this source code in the file LICENSE. |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
namespace iCom\SolrClient\Client; |
|
15
|
|
|
|
|
16
|
|
|
use iCom\SolrClient\Client; |
|
17
|
|
|
use iCom\SolrClient\Exception\CommunicationError; |
|
18
|
|
|
use iCom\SolrClient\JsonQuery; |
|
19
|
|
|
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface; |
|
20
|
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface; |
|
21
|
|
|
|
|
22
|
|
|
final class SymfonyClient implements Client |
|
23
|
|
|
{ |
|
24
|
|
|
private HttpClientInterface $httpClient; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct(HttpClientInterface $httpClient) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->httpClient = $httpClient; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function select($jsonBody): array |
|
32
|
|
|
{ |
|
33
|
|
|
return $this->send('GET', 'select', $jsonBody); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function update($jsonBody): array |
|
37
|
|
|
{ |
|
38
|
|
|
return $this->send('POST', 'update', $jsonBody); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @param mixed $body |
|
43
|
|
|
*/ |
|
44
|
|
|
private function send(string $method, string $url, $body = null): array |
|
45
|
|
|
{ |
|
46
|
|
|
$options = ['headers' => [ |
|
47
|
|
|
'Accept' => 'application/json', |
|
48
|
|
|
'Content-Type' => 'application/json', |
|
49
|
|
|
]]; |
|
50
|
|
|
|
|
51
|
|
|
if (null !== $body) { |
|
52
|
|
|
$options['body'] = $this->getBody($body); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
try { |
|
56
|
|
|
$response = $this->httpClient->request($method, $url, $options); |
|
57
|
|
|
|
|
58
|
|
|
return $response->toArray(); |
|
59
|
|
|
} catch (ExceptionInterface $e) { |
|
60
|
|
|
throw CommunicationError::fromUpstreamException($e); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param mixed $body |
|
66
|
|
|
*/ |
|
67
|
|
|
private function getBody($body): string |
|
68
|
|
|
{ |
|
69
|
|
|
if ($body instanceof JsonQuery) { |
|
70
|
|
|
return $body->toJson(); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
if (!\is_string($body) || '{' !== $body[0]) { |
|
74
|
|
|
throw new \InvalidArgumentException(sprintf('Client can accept only string or "%s", but "%s" given.', JsonQuery::class, \get_debug_type($body))); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
return $body; |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|