Skip to content

Commit ccee923

Browse files
committed
Refactor interfaces to support updated API
1 parent 9ff00cb commit ccee923

6 files changed

Lines changed: 157 additions & 54 deletions

File tree

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
"require": {
3333
"php": ">=7.4",
3434
"guzzlehttp/guzzle": "^7.0",
35-
"ext-json": "*"
35+
"ext-json": "*",
36+
"monolog/monolog": "^2.1"
3637
},
3738
"require-dev": {
3839
"squizlabs/php_codesniffer": "3.*"

examples/collection_operations.php

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -104,37 +104,40 @@
104104
]
105105
)
106106
);
107-
108-
// You can also upsert a document, by passing an upsert => true option:
109-
//$client->collections['books']->documents->create(
110-
// [
111-
// 'id' => '1',
112-
// 'original_publication_year' => 2008,
113-
// 'authors' => [
114-
// 'Suzanne Collins',
115-
// ],
116-
// 'average_rating' => 4.34,
117-
// 'publication_year' => 2008,
118-
// 'publication_year_facet' => '2008',
119-
// 'authors_facet' => [
120-
// 'Suzanne Collins',
121-
// ],
122-
// 'title' => 'The Hunger Games',
123-
// 'image_url' => 'https://images.gr-assets.com/books/1447303603m/2767052.jpg',
124-
// 'ratings_count' => 4780653,
125-
// ],
126-
// ['upsert' => true]
127-
//);
128107
echo "--------Create Document-------\n";
129108
echo "\n";
109+
110+
// echo "--------Upsert Document-------\n";
111+
// print_r(
112+
// $client->collections['books']->documents->upsert(
113+
// [
114+
// 'id' => '1',
115+
// 'original_publication_year' => 2008,
116+
// 'authors' => [
117+
// 'Suzanne Collins',
118+
// ],
119+
// 'average_rating' => 4.34,
120+
// 'publication_year' => 2008,
121+
// 'publication_year_facet' => '2008',
122+
// 'authors_facet' => [
123+
// 'Suzanne Collins',
124+
// ],
125+
// 'title' => 'The Hunger Games',
126+
// 'image_url' => 'https://images.gr-assets.com/books/1447303603m/2767052.jpg',
127+
// 'ratings_count' => 4780653,
128+
// ]
129+
// )
130+
// );
131+
// echo "--------Upsert Document-------\n";
132+
// echo "\n";
133+
130134
echo "--------Export Documents-------\n";
131135
$exportedDocStrs = $client->collections['books']->documents->export();
132136
print_r($exportedDocStrs);
133137
echo "--------Export Documents-------\n";
134138
echo "\n";
135139
echo "--------Update Single Document-------\n";
136140
print_r($client->collections['books']->documents['1']->update([
137-
'id' => '1',
138141
'average_rating' => 4.5,
139142
]));
140143
echo "--------Update Single Document-------\n";
@@ -160,24 +163,24 @@
160163
echo "--------Delete Document-------\n";
161164
echo "\n";
162165
echo "--------Import Documents-------\n";
163-
$docsToImport = [];
166+
$docsToImport = [];
164167
$exportedDocStrsArray = explode('\n', $exportedDocStrs);
165168
foreach ($exportedDocStrsArray as $exportedDocStr) {
166169
$docsToImport[] = json_decode($exportedDocStr, true);
167170
}
168171
$importRes =
169-
$client->collections['books']->documents->createMany($docsToImport);
172+
$client->collections['books']->documents->import($docsToImport);
170173
print_r($importRes);
171174

172175
// Or if you have documents in JSONL format, and want to save the overhead of parsing JSON,
173-
// you can also use the import method:
174-
// $client->collections['books']->documents->import($documentsJSONLString);
176+
// you can also pass in a JSONL string of documents
177+
// $client->collections['books']->documents->import($exportedDocStrsArray);
175178
echo "--------Import Documents-------\n";
176179
echo "\n";
177180
echo "--------Upsert Documents-------\n";
178181
$upsertRes =
179-
$client->collections['books']->documents->createMany($docsToImport, [
180-
'upsert' => true
182+
$client->collections['books']->documents->import($docsToImport, [
183+
'mode' => 'upsert'
181184
]);
182185
print_r($upsertRes);
183186
echo "--------Upsert Documents-------\n";

src/ApiCall.php

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Exception;
66
use GuzzleHttp\Exception\GuzzleException;
7+
use Psr\Log\LoggerInterface;
78
use Typesense\Lib\Node;
89
use Typesense\Lib\Configuration;
910
use GuzzleHttp\Exception\ClientException;
@@ -55,6 +56,11 @@ class ApiCall
5556
*/
5657
private int $nodeIndex;
5758

59+
/**
60+
* @var LoggerInterface
61+
*/
62+
public LoggerInterface $logger;
63+
5864
/**
5965
* ApiCall constructor.
6066
*
@@ -63,6 +69,7 @@ class ApiCall
6369
public function __construct(Configuration $config)
6470
{
6571
$this->config = $config;
72+
$this->logger = $config->getLogger();
6673
$this->client = new \GuzzleHttp\Client();
6774
self::$nodes = $this->config->getNodes();
6875
self::$nearestNode = $this->config->getNearestNode();
@@ -123,29 +130,50 @@ public function post(string $endPoint, $body, bool $asJson = true, array $queryP
123130
* @param string $endPoint
124131
* @param array $body
125132
*
133+
* @param bool $asJson
126134
* @param array $queryParameters
127135
*
128136
* @return array
129137
* @throws TypesenseClientError|GuzzleException
130138
*/
131-
public function put(string $endPoint, array $body, array $queryParameters = []): array
139+
public function put(string $endPoint, array $body, bool $asJson = true, array $queryParameters = []): array
132140
{
133-
return $this->makeRequest('put', $endPoint, true, [
141+
return $this->makeRequest('put', $endPoint, $asJson, [
134142
'data' => $body ?? [],
135143
'query' => $queryParameters ?? []
136144
]);
137145
}
138146

139147
/**
140148
* @param string $endPoint
149+
* @param array $body
150+
*
151+
* @param bool $asJson
141152
* @param array $queryParameters
142153
*
143154
* @return array
144155
* @throws TypesenseClientError|GuzzleException
145156
*/
146-
public function delete(string $endPoint, array $queryParameters = []): array
157+
public function patch(string $endPoint, array $body, bool $asJson = true, array $queryParameters = []): array
147158
{
148-
return $this->makeRequest('delete', $endPoint, true, [
159+
return $this->makeRequest('patch', $endPoint, $asJson, [
160+
'data' => $body ?? [],
161+
'query' => $queryParameters ?? []
162+
]);
163+
}
164+
165+
/**
166+
* @param string $endPoint
167+
*
168+
* @param bool $asJson
169+
* @param array $queryParameters
170+
*
171+
* @return array
172+
* @throws TypesenseClientError|GuzzleException
173+
*/
174+
public function delete(string $endPoint, bool $asJson = true, array $queryParameters = []): array
175+
{
176+
return $this->makeRequest('delete', $endPoint, $asJson, [
149177
'query' => $queryParameters ?? []
150178
]);
151179
}
@@ -330,4 +358,12 @@ public function getException(int $httpCode): TypesenseClientError
330358
return new TypesenseClientError();
331359
}
332360
}
361+
362+
/**
363+
* @return LoggerInterface
364+
*/
365+
public function getLogger()
366+
{
367+
return $this->logger;
368+
}
333369
}

src/Document.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public function retrieve(): array
7575
*/
7676
public function update(array $partialDocument): array
7777
{
78-
return $this->apiCall->put($this->endpointPath(), $partialDocument);
78+
return $this->apiCall->patch($this->endpointPath(), $partialDocument);
7979
}
8080

8181
/**

src/Documents.php

Lines changed: 58 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ class Documents implements \ArrayAccess
4141
public function __construct(string $collectionName, ApiCall $apiCall)
4242
{
4343
$this->collectionName = $collectionName;
44-
$this->apiCall = $apiCall;
44+
$this->apiCall = $apiCall;
4545
}
4646

4747
/**
@@ -56,14 +56,35 @@ private function endPointPath(string $action = ''): string
5656

5757
/**
5858
* @param array $document
59-
* @param array $options
6059
*
6160
* @return array
6261
* @throws TypesenseClientError|GuzzleException
6362
*/
64-
public function create(array $document, array $options = []): array
63+
public function create(array $document): array
64+
{
65+
return $this->apiCall->post($this->endPointPath(''), $document, true);
66+
}
67+
68+
/**
69+
* @param array $document
70+
*
71+
* @return array
72+
* @throws TypesenseClientError|GuzzleException
73+
*/
74+
public function upsert(array $document): array
75+
{
76+
return $this->apiCall->post($this->endPointPath(''), $document, true, ['mode' => 'upsert']);
77+
}
78+
79+
/**
80+
* @param array $document
81+
*
82+
* @return array
83+
* @throws TypesenseClientError|GuzzleException
84+
*/
85+
public function update(array $document): array
6586
{
66-
return $this->apiCall->post($this->endPointPath(''), $document, true, $options);
87+
return $this->apiCall->post($this->endPointPath(''), $document, true, ['mode' => 'update']);
6788
}
6889

6990
/**
@@ -75,32 +96,49 @@ public function create(array $document, array $options = []): array
7596
*/
7697
public function createMany(array $documents, array $options = []): array
7798
{
78-
$res = $this->import(
79-
implode(
80-
"\n",
81-
array_map(
82-
static fn(array $document) => json_encode($document, JSON_THROW_ON_ERROR),
83-
$documents
84-
)
85-
),
86-
$options
99+
$this->apiCall->getLogger()->warning(
100+
"createMany is deprecated and will be removed in a future version. " .
101+
"Use import instead, which now takes both an array of documents or a JSONL string of documents"
87102
);
88-
return array_map(static function ($item) {
89-
return json_decode($item, true, 512, JSON_THROW_ON_ERROR);
90-
}, explode("\n", $res));
103+
return $this->import($documents, $options);
91104
}
92105

93106
/**
94-
* @param string $documents
107+
* @param string|array $documents
95108
* @param array $options
96109
*
97-
* @return string
110+
* @return string|array
98111
* @throws TypesenseClientError
99112
* @throws GuzzleException
113+
* @throws \JsonException
100114
*/
101-
public function import(string $documents, array $options = []): string
115+
public function import($documents, array $options = [])
102116
{
103-
return $this->apiCall->post($this->endPointPath('import'), $documents, false, $options);
117+
if (is_array($documents)) {
118+
$documentsInJSONLFormat = implode(
119+
"\n",
120+
array_map(
121+
static fn(array $document) => json_encode($document, JSON_THROW_ON_ERROR),
122+
$documents
123+
)
124+
);
125+
} else {
126+
$documentsInJSONLFormat = $documents;
127+
}
128+
$resultsInJSONLFormat = $this->apiCall->post(
129+
$this->endPointPath('import'),
130+
$documentsInJSONLFormat,
131+
false,
132+
$options
133+
);
134+
135+
if (is_array($documents)) {
136+
return array_map(static function ($item) {
137+
return json_decode($item, true, 512, JSON_THROW_ON_ERROR);
138+
}, explode("\n", $resultsInJSONLFormat));
139+
} else {
140+
return $resultsInJSONLFormat;
141+
}
104142
}
105143

106144
/**

src/Lib/Configuration.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
namespace Typesense\Lib;
44

55
use Typesense\Exceptions\ConfigError;
6+
use Psr\Log\LoggerInterface;
7+
use Monolog\Logger;
8+
use Monolog\Handler\StreamHandler;
69

710
/**
811
* Class Configuration
@@ -49,6 +52,16 @@ class Configuration
4952
*/
5053
private int $healthCheckIntervalSeconds;
5154

55+
/**
56+
* @var LoggerInterface
57+
*/
58+
private LoggerInterface $logger;
59+
60+
/**
61+
* @var int
62+
*/
63+
private int $logLevel;
64+
5265
/**
5366
* Configuration constructor.
5467
*
@@ -83,6 +96,10 @@ public function __construct(array $config)
8396
$this->healthCheckIntervalSeconds = (int)($config['healthcheck_interval_seconds'] ?? 60);
8497
$this->numRetries = (float)($config['num_retries'] ?? 3);
8598
$this->retryIntervalSeconds = (float)($config['retry_interval_seconds'] ?? 1.0);
99+
100+
$this->logLevel = $config->logLevel ?? Logger::WARNING;
101+
$this->logger = new Logger('typesense');
102+
$this->logger->pushHandler(new StreamHandler('php://stdout', $this->logLevel));
86103
}
87104

88105
/**
@@ -187,4 +204,12 @@ public function getHealthCheckIntervalSeconds()
187204
{
188205
return $this->healthCheckIntervalSeconds;
189206
}
207+
208+
/**
209+
* @return LoggerInterface
210+
*/
211+
public function getLogger()
212+
{
213+
return $this->logger;
214+
}
190215
}

0 commit comments

Comments
 (0)