From 46982567dbb000a0cc8781ada5296244ef88cafb Mon Sep 17 00:00:00 2001 From: Tomas Date: Wed, 9 Apr 2025 12:42:12 +0300 Subject: [PATCH 01/51] Bump PHP requirement to 8.1 --- .php-cs-fixer.dist.php | 3 +-- composer.json | 6 +++--- src/Client.php | 2 +- src/Endpoints/Keys.php | 2 +- src/Http/Client.php | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 897ce305..c42da808 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -16,8 +16,7 @@ 'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'], 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], 'php_unit_strict' => true, - // @todo: when we'll support only PHP 8.0 and upper, we can enable `parameters` for `trailing_comma_in_multiline` rule - 'trailing_comma_in_multiline' => ['after_heredoc' => true, 'elements' => ['array_destructuring', 'arrays', 'match'/* , 'parameters' */]], + 'trailing_comma_in_multiline' => ['after_heredoc' => true, 'elements' => ['array_destructuring', 'arrays', 'match', 'parameters']], ]) ->setRiskyAllowed(true) ->setFinder($finder); diff --git a/composer.json b/composer.json index fdf26422..aafe621a 100644 --- a/composer.json +++ b/composer.json @@ -31,9 +31,9 @@ ], "minimum-stability": "stable", "require": { - "php": "^7.4 || ^8.0", + "php": "^8.1", "ext-json": "*", - "php-http/discovery": "^1.7", + "php-http/discovery": "^1.19", "psr/http-client": "^1.0", "symfony/polyfill-php81": "^1.33" }, @@ -54,7 +54,7 @@ "symfony/http-client": "Use Symfony Http client" }, "require-dev": { - "phpunit/phpunit": "^9.5 || ^10.5", + "phpunit/phpunit": "^10.5", "php-cs-fixer/shim": "^3.59.3", "http-interop/http-factory-guzzle": "^1.2.0", "phpstan/phpstan": "^2.0", diff --git a/src/Client.php b/src/Client.php index 9baf3f3c..7fb7ee9c 100644 --- a/src/Client.php +++ b/src/Client.php @@ -53,7 +53,7 @@ public function __construct( ?ClientInterface $httpClient = null, ?RequestFactoryInterface $requestFactory = null, array $clientAgents = [], - ?StreamFactoryInterface $streamFactory = null + ?StreamFactoryInterface $streamFactory = null, ) { $this->http = new MeilisearchClientAdapter($url, $apiKey, $httpClient, $requestFactory, $clientAgents, $streamFactory); $this->chats = new ChatWorkspaces($this->http); diff --git a/src/Endpoints/Keys.php b/src/Endpoints/Keys.php index bfe09efe..eb0b7067 100644 --- a/src/Endpoints/Keys.php +++ b/src/Endpoints/Keys.php @@ -95,7 +95,7 @@ protected function createDate($attribute): ?\DateTimeInterface return null; } - if (false === strpos($attribute, '.')) { + if (!str_contains($attribute, '.')) { $date = \DateTimeImmutable::createFromFormat(\DateTimeInterface::ATOM, $attribute); } else { $attribute = preg_replace('/(\.\d{6})\d+/', '$1', $attribute, 1); diff --git a/src/Http/Client.php b/src/Http/Client.php index 7039dc4b..d0023153 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -46,7 +46,7 @@ public function __construct( ?ClientInterface $httpClient = null, ?RequestFactoryInterface $reqFactory = null, array $clientAgents = [], - ?StreamFactoryInterface $streamFactory = null + ?StreamFactoryInterface $streamFactory = null, ) { $this->baseUrl = $url; $this->http = $httpClient ?? Psr18ClientDiscovery::find(); From 8b9a4428213bf6a5c6e2315c3e6dc37d30d49abc Mon Sep 17 00:00:00 2001 From: Tomas Date: Wed, 9 Apr 2025 14:44:29 +0300 Subject: [PATCH 02/51] Add missing types --- src/Contracts/Data.php | 11 +--- src/Contracts/Http.php | 6 +- src/Contracts/SimilarDocumentsQuery.php | 21 +++---- src/Endpoints/Batches.php | 2 +- src/Endpoints/Delegates/HandlesBatches.php | 2 +- src/Endpoints/Delegates/HandlesDocuments.php | 49 ++++++--------- src/Endpoints/Delegates/HandlesIndex.php | 18 ++++++ src/Endpoints/Delegates/HandlesTasks.php | 8 ++- src/Endpoints/Delegates/TasksQueryTrait.php | 2 +- src/Endpoints/Indexes.php | 8 +-- src/Endpoints/Keys.php | 11 +++- src/Endpoints/Tasks.php | 6 +- src/Endpoints/TenantToken.php | 6 +- src/Exceptions/ApiException.php | 8 +-- src/Exceptions/CommunicationException.php | 2 +- src/Exceptions/InvalidArgumentException.php | 9 --- .../InvalidResponseBodyException.php | 6 +- src/Exceptions/TimeOutException.php | 6 +- src/Http/Serialize/Json.php | 4 +- src/Http/Serialize/SerializerInterface.php | 4 +- tests/Endpoints/DocumentsTest.php | 59 ++++--------------- 21 files changed, 104 insertions(+), 144 deletions(-) diff --git a/src/Contracts/Data.php b/src/Contracts/Data.php index 5ed52a79..4c734f69 100644 --- a/src/Contracts/Data.php +++ b/src/Contracts/Data.php @@ -6,7 +6,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate { - protected $data = []; + protected array $data = []; public function __construct(array $data = []) { @@ -28,14 +28,9 @@ public function offsetUnset($offset): void unset($this->data[$offset]); } - #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet($offset): mixed { - if (isset($this->data[$offset])) { - return $this->data[$offset]; - } - - return null; + return $this->data[$offset] ?? null; } public function count(): int diff --git a/src/Contracts/Http.php b/src/Contracts/Http.php index 27b6722b..812c2809 100644 --- a/src/Contracts/Http.php +++ b/src/Contracts/Http.php @@ -21,7 +21,7 @@ public function get(string $path, array $query = []); * @throws ApiException * @throws \JsonException */ - public function post(string $path, $body = null, array $query = [], ?string $contentType = null); + public function post(string $path, mixed $body = null, array $query = [], ?string $contentType = null); /** * @param non-empty-string|null $contentType @@ -29,13 +29,13 @@ public function post(string $path, $body = null, array $query = [], ?string $con * @throws ApiException * @throws \JsonException */ - public function put(string $path, $body = null, array $query = [], ?string $contentType = null); + public function put(string $path, mixed $body = null, array $query = [], ?string $contentType = null); /** * @throws ApiException * @throws \JsonException */ - public function patch(string $path, $body = null, array $query = []); + public function patch(string $path, mixed $body = null, array $query = []); /** * @throws ApiException diff --git a/src/Contracts/SimilarDocumentsQuery.php b/src/Contracts/SimilarDocumentsQuery.php index 04c65ae3..a9285c5a 100644 --- a/src/Contracts/SimilarDocumentsQuery.php +++ b/src/Contracts/SimilarDocumentsQuery.php @@ -7,9 +7,9 @@ class SimilarDocumentsQuery { /** - * @var int|string + * @var int|non-empty-string */ - private $id; + private int|string $id; /** * @var non-empty-string @@ -42,16 +42,13 @@ class SimilarDocumentsQuery */ private ?array $filter = null; - /** - * @var int|float|null - */ - private $rankingScoreThreshold; + private int|float|null $rankingScoreThreshold = null; /** - * @param int|string $id - * @param non-empty-string $embedder + * @param int|non-empty-string $id + * @param non-empty-string $embedder */ - public function __construct($id, string $embedder) + public function __construct(int|string $id, string $embedder) { $this->id = $id; $this->embedder = $embedder; @@ -142,11 +139,9 @@ public function setRetrieveVectors(?bool $retrieveVectors): self } /** - * @param int|float|null $rankingScoreThreshold - * * @return $this */ - public function setRankingScoreThreshold($rankingScoreThreshold): self + public function setRankingScoreThreshold(int|float|null $rankingScoreThreshold): self { $this->rankingScoreThreshold = $rankingScoreThreshold; @@ -155,7 +150,7 @@ public function setRankingScoreThreshold($rankingScoreThreshold): self /** * @return array{ - * id: int|string, + * id: int|non-empty-string, * embedder: non-empty-string, * offset?: non-negative-int, * limit?: positive-int, diff --git a/src/Endpoints/Batches.php b/src/Endpoints/Batches.php index 1a00b475..6562b93c 100644 --- a/src/Endpoints/Batches.php +++ b/src/Endpoints/Batches.php @@ -10,7 +10,7 @@ class Batches extends Endpoint { protected const PATH = '/batches'; - public function get($batchUid): array + public function get(int $batchUid): array { return $this->http->get(self::PATH.'/'.$batchUid); } diff --git a/src/Endpoints/Delegates/HandlesBatches.php b/src/Endpoints/Delegates/HandlesBatches.php index 5c53bc9d..542bd221 100644 --- a/src/Endpoints/Delegates/HandlesBatches.php +++ b/src/Endpoints/Delegates/HandlesBatches.php @@ -12,7 +12,7 @@ trait HandlesBatches { protected Batches $batches; - public function getBatch($uid): array + public function getBatch(int $uid): array { return $this->batches->get($uid); } diff --git a/src/Endpoints/Delegates/HandlesDocuments.php b/src/Endpoints/Delegates/HandlesDocuments.php index f461d2bf..70eee739 100644 --- a/src/Endpoints/Delegates/HandlesDocuments.php +++ b/src/Endpoints/Delegates/HandlesDocuments.php @@ -7,14 +7,12 @@ use Meilisearch\Contracts\DocumentsQuery; use Meilisearch\Contracts\DocumentsResults; use Meilisearch\Exceptions\ApiException; -use Meilisearch\Exceptions\InvalidArgumentException; use Meilisearch\Exceptions\InvalidResponseBodyException; trait HandlesDocuments { - public function getDocument($documentId, ?array $fields = null) + public function getDocument(string|int $documentId, ?array $fields = null): array { - $this->assertValidDocumentId($documentId); $query = isset($fields) ? ['fields' => implode(',', $fields)] : []; return $this->http->get(self::PATH.'/'.$this->uid.'/documents/'.$documentId, $query); @@ -38,27 +36,27 @@ public function getDocuments(?DocumentsQuery $options = null): DocumentsResults } } - public function addDocuments(array $documents, ?string $primaryKey = null) + public function addDocuments(array $documents, ?string $primaryKey = null): array { return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey]); } - public function addDocumentsJson(string $documents, ?string $primaryKey = null) + public function addDocumentsJson(string $documents, ?string $primaryKey = null): array { return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json'); } - public function addDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null) + public function addDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): array { return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv'); } - public function addDocumentsNdjson(string $documents, ?string $primaryKey = null) + public function addDocumentsNdjson(string $documents, ?string $primaryKey = null): array { return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson'); } - public function addDocumentsInBatches(array $documents, ?int $batchSize = 1000, ?string $primaryKey = null) + public function addDocumentsInBatches(array $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -69,7 +67,7 @@ public function addDocumentsInBatches(array $documents, ?int $batchSize = 1000, return $promises; } - public function addDocumentsCsvInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null, ?string $delimiter = null) + public function addDocumentsCsvInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null, ?string $delimiter = null): array { $promises = []; @@ -80,7 +78,7 @@ public function addDocumentsCsvInBatches(string $documents, ?int $batchSize = 10 return $promises; } - public function addDocumentsNdjsonInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null) + public function addDocumentsNdjsonInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -91,27 +89,27 @@ public function addDocumentsNdjsonInBatches(string $documents, ?int $batchSize = return $promises; } - public function updateDocuments(array $documents, ?string $primaryKey = null) + public function updateDocuments(array $documents, ?string $primaryKey = null): array { return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey]); } - public function updateDocumentsJson(string $documents, ?string $primaryKey = null) + public function updateDocumentsJson(string $documents, ?string $primaryKey = null): array { return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json'); } - public function updateDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null) + public function updateDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): array { return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv'); } - public function updateDocumentsNdjson(string $documents, ?string $primaryKey = null) + public function updateDocumentsNdjson(string $documents, ?string $primaryKey = null): array { return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson'); } - public function updateDocumentsInBatches(array $documents, ?int $batchSize = 1000, ?string $primaryKey = null) + public function updateDocumentsInBatches(array $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -122,7 +120,7 @@ public function updateDocumentsInBatches(array $documents, ?int $batchSize = 100 return $promises; } - public function updateDocumentsCsvInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null, ?string $delimiter = null) + public function updateDocumentsCsvInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null, ?string $delimiter = null): array { $promises = []; @@ -133,7 +131,7 @@ public function updateDocumentsCsvInBatches(string $documents, ?int $batchSize = return $promises; } - public function updateDocumentsNdjsonInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null) + public function updateDocumentsNdjsonInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -154,7 +152,7 @@ public function updateDocumentsNdjsonInBatches(string $documents, ?int $batchSiz * @param non-empty-string $function * @param array{filter?: non-empty-string|list|null, context?: array} $options */ - public function updateDocumentsByFunction(string $function, array $options = []) + public function updateDocumentsByFunction(string $function, array $options = []): array { return $this->http->post(self::PATH.'/'.$this->uid.'/documents/edit', array_merge(['function' => $function], $options)); } @@ -164,10 +162,8 @@ public function deleteAllDocuments(): array return $this->http->delete(self::PATH.'/'.$this->uid.'/documents'); } - public function deleteDocument($documentId): array + public function deleteDocument(string|int $documentId): array { - $this->assertValidDocumentId($documentId); - return $this->http->delete(self::PATH.'/'.$this->uid.'/documents/'.$documentId); } @@ -186,17 +182,6 @@ public function deleteDocuments(array $options): array } } - private function assertValidDocumentId($documentId): void - { - if (!\is_string($documentId) && !\is_int($documentId)) { - throw InvalidArgumentException::invalidType('documentId', ['string', 'int']); - } - - if (\is_string($documentId) && '' === trim($documentId)) { - throw InvalidArgumentException::emptyArgument('documentId'); - } - } - private static function batchCsvString(string $documents, int $batchSize): \Generator { $parsedDocuments = preg_split("/\r\n|\n|\r/", trim($documents)); diff --git a/src/Endpoints/Delegates/HandlesIndex.php b/src/Endpoints/Delegates/HandlesIndex.php index 983107ad..75b84e63 100644 --- a/src/Endpoints/Delegates/HandlesIndex.php +++ b/src/Endpoints/Delegates/HandlesIndex.php @@ -17,31 +17,49 @@ public function getIndexes(?IndexesQuery $options = null): IndexesResults return $this->index->all($options ?? null); } + /** + * @param non-empty-string $uid + */ public function getRawIndex(string $uid): array { return $this->index($uid)->fetchRawInfo(); } + /** + * @param non-empty-string $uid + */ public function index(string $uid): Indexes { return new Indexes($this->http, $uid); } + /** + * @param non-empty-string $uid + */ public function getIndex(string $uid): Indexes { return $this->index($uid)->fetchInfo(); } + /** + * @param non-empty-string $uid + */ public function deleteIndex(string $uid): array { return $this->index($uid)->delete(); } + /** + * @param non-empty-string $uid + */ public function createIndex(string $uid, array $options = []): array { return $this->index->create($uid, $options); } + /** + * @param non-empty-string $uid + */ public function updateIndex(string $uid, array $options = []): array { return $this->index($uid)->update($options); diff --git a/src/Endpoints/Delegates/HandlesTasks.php b/src/Endpoints/Delegates/HandlesTasks.php index efdb6432..96e108cb 100644 --- a/src/Endpoints/Delegates/HandlesTasks.php +++ b/src/Endpoints/Delegates/HandlesTasks.php @@ -15,7 +15,7 @@ trait HandlesTasks { protected Tasks $tasks; - public function getTask($uid): array + public function getTask(int $uid): array { return $this->tasks->get($uid); } @@ -42,15 +42,17 @@ public function cancelTasks(?CancelTasksQuery $options = null): array /** * @throws TimeOutException */ - public function waitForTask($uid, int $timeoutInMs = 5000, int $intervalInMs = 50): array + public function waitForTask(int $uid, int $timeoutInMs = 5000, int $intervalInMs = 50): array { return $this->tasks->waitTask($uid, $timeoutInMs, $intervalInMs); } /** + * @param array $uids + * * @throws TimeOutException */ - public function waitForTasks($uids, int $timeoutInMs = 5000, int $intervalInMs = 50): array + public function waitForTasks(array $uids, int $timeoutInMs = 5000, int $intervalInMs = 50): array { return $this->tasks->waitTasks($uids, $timeoutInMs, $intervalInMs); } diff --git a/src/Endpoints/Delegates/TasksQueryTrait.php b/src/Endpoints/Delegates/TasksQueryTrait.php index 058f5bbc..00a545e5 100644 --- a/src/Endpoints/Delegates/TasksQueryTrait.php +++ b/src/Endpoints/Delegates/TasksQueryTrait.php @@ -148,7 +148,7 @@ protected function baseArray(): array private function formatDate(?\DateTimeInterface $date): ?string { - return null !== $date ? $date->format(\DateTimeInterface::RFC3339) : null; + return $date?->format(\DateTimeInterface::RFC3339); } private function formatArray(?array $array): ?string diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index 3af12493..e4a020ca 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -136,7 +136,7 @@ public function fetchInfo(): self return $this->fill($response); } - public function update($body): array + public function update(array $body): array { return $this->http->patch(self::PATH.'/'.$this->uid, $body); } @@ -156,7 +156,7 @@ public function swapIndexes(array $indexes): array // Tasks - public function getTask($uid): array + public function getTask(int $uid): array { return $this->http->get('/tasks/'.$uid); } @@ -179,11 +179,9 @@ public function getTasks(?TasksQuery $options = null): TasksResults // Search /** - * @return SearchResult|array - * * @phpstan-return ($options is array{raw: true|non-falsy-string|positive-int} ? array : SearchResult) */ - public function search(?string $query, array $searchParams = [], array $options = []) + public function search(?string $query, array $searchParams = [], array $options = []): SearchResult|array { $result = $this->rawSearch($query, $searchParams); diff --git a/src/Endpoints/Keys.php b/src/Endpoints/Keys.php index eb0b7067..19e084b1 100644 --- a/src/Endpoints/Keys.php +++ b/src/Endpoints/Keys.php @@ -150,7 +150,10 @@ public function getUpdatedAt(): ?\DateTimeInterface return $this->updatedAt; } - public function get($keyOrUid): self + /** + * @param non-empty-string $keyOrUid + */ + public function get(string $keyOrUid): self { $response = $this->http->get(self::PATH.'/'.$keyOrUid); @@ -188,6 +191,9 @@ public function create(array $options = []): self return $this->fill($response); } + /** + * @param non-empty-string $keyOrUid + */ public function update(string $keyOrUid, array $options = []): self { $data = array_intersect_key($options, array_flip(['description', 'name'])); @@ -196,6 +202,9 @@ public function update(string $keyOrUid, array $options = []): self return $this->fill($response); } + /** + * @param non-empty-string $keyOrUid + */ public function delete(string $keyOrUid): array { return $this->http->delete(self::PATH.'/'.$keyOrUid) ?? []; diff --git a/src/Endpoints/Tasks.php b/src/Endpoints/Tasks.php index 1d6d2b3f..b80f3481 100644 --- a/src/Endpoints/Tasks.php +++ b/src/Endpoints/Tasks.php @@ -13,7 +13,7 @@ class Tasks extends Endpoint { protected const PATH = '/tasks'; - public function get($taskUid): array + public function get(int $taskUid): array { return $this->http->get(self::PATH.'/'.$taskUid); } @@ -40,7 +40,7 @@ public function deleteTasks(?DeleteTasksQuery $options): array /** * @throws TimeOutException */ - public function waitTask($taskUid, int $timeoutInMs, int $intervalInMs): array + public function waitTask(int $taskUid, int $timeoutInMs, int $intervalInMs): array { $timeoutTemp = 0; @@ -59,6 +59,8 @@ public function waitTask($taskUid, int $timeoutInMs, int $intervalInMs): array } /** + * @param array $taskUids + * * @throws TimeOutException */ public function waitTasks(array $taskUids, int $timeoutInMs, int $intervalInMs): array diff --git a/src/Endpoints/TenantToken.php b/src/Endpoints/TenantToken.php index 4bf4f9c0..9158e912 100644 --- a/src/Endpoints/TenantToken.php +++ b/src/Endpoints/TenantToken.php @@ -18,12 +18,12 @@ private function base64url_encode(string $data): string /** * @param array{apiKey?: ?string, expiresAt?: ?\DateTimeInterface} $options */ - private function validateTenantTokenArguments($searchRules, array $options = []): void + private function validateTenantTokenArguments(array|object $searchRules, array $options = []): void { if (!isset($options['apiKey']) || ('' === $options['apiKey'] || \strlen($options['apiKey']) <= 8)) { throw InvalidArgumentException::emptyArgument('api key'); } - if ((!\is_array($searchRules) || [] === $searchRules) && !\is_object($searchRules)) { + if ([] === $searchRules) { throw InvalidArgumentException::emptyArgument('search rules'); } if (isset($options['expiresAt']) && new \DateTimeImmutable() > $options['expiresAt']) { @@ -40,7 +40,7 @@ private function validateTenantTokenArguments($searchRules, array $options = []) * * @param array{apiKey?: ?string, expiresAt?: ?\DateTimeInterface} $options */ - public function generateTenantToken(string $uid, $searchRules, array $options = []): string + public function generateTenantToken(string $uid, array|object $searchRules, array $options = []): string { if (!isset($options['apiKey']) || '' === $options['apiKey']) { $options['apiKey'] = $this->apiKey; diff --git a/src/Exceptions/ApiException.php b/src/Exceptions/ApiException.php index f7ebc1e9..98493447 100644 --- a/src/Exceptions/ApiException.php +++ b/src/Exceptions/ApiException.php @@ -13,11 +13,11 @@ class ApiException extends \Exception implements ExceptionInterface public ?string $errorCode; public ?string $errorType; public ?string $errorLink; - public $httpBody; + public mixed $httpBody; public const HINT_MESSAGE = "Hint: It might not be working because maybe you're not up to date with the Meilisearch version that `%s` call requires."; - public function __construct(ResponseInterface $response, $httpBody, $previous = null) + public function __construct(ResponseInterface $response, mixed $httpBody, ?\Throwable $previous = null) { $this->httpBody = $httpBody; $this->httpStatus = $response->getStatusCode(); @@ -29,7 +29,7 @@ public function __construct(ResponseInterface $response, $httpBody, $previous = parent::__construct($this->message, $this->httpStatus, $previous); } - public function __toString() + public function __toString(): string { $base = 'Meilisearch ApiException: Http Status: '.$this->httpStatus; @@ -88,7 +88,7 @@ private function getErrorLinkFromHttpBody(): ?string return null; } - public static function rethrowWithHint(\Exception $e, string $methodName) + public static function rethrowWithHint(\Throwable $e, string $methodName): \Exception { return new \Exception(\sprintf(self::HINT_MESSAGE, $methodName), 0, $e); } diff --git a/src/Exceptions/CommunicationException.php b/src/Exceptions/CommunicationException.php index e4fc8a97..7b5504b7 100644 --- a/src/Exceptions/CommunicationException.php +++ b/src/Exceptions/CommunicationException.php @@ -6,7 +6,7 @@ class CommunicationException extends \Exception implements ExceptionInterface { - public function __toString() + public function __toString(): string { return 'Meilisearch CommunicationException: '.$this->getMessage(); } diff --git a/src/Exceptions/InvalidArgumentException.php b/src/Exceptions/InvalidArgumentException.php index 04b31f15..90a62206 100644 --- a/src/Exceptions/InvalidArgumentException.php +++ b/src/Exceptions/InvalidArgumentException.php @@ -6,15 +6,6 @@ final class InvalidArgumentException extends \Exception implements ExceptionInterface { - public static function invalidType(string $argumentName, array $validTypes): self - { - return new self( - \sprintf('Argument "%s" is not a valid type! Please provide an argument that is of type: "%s"', $argumentName, implode('","', $validTypes)), - 400, - null - ); - } - public static function emptyArgument(string $argumentName): self { return new self( diff --git a/src/Exceptions/InvalidResponseBodyException.php b/src/Exceptions/InvalidResponseBodyException.php index 5245df44..9416664d 100644 --- a/src/Exceptions/InvalidResponseBodyException.php +++ b/src/Exceptions/InvalidResponseBodyException.php @@ -8,8 +8,8 @@ class InvalidResponseBodyException extends \Exception implements ExceptionInterface { - public $httpStatus = 0; - public $httpBody; + public int $httpStatus = 0; + public mixed $httpBody; public $message; public function __construct(ResponseInterface $response, $httpBody, $previous = null) @@ -21,7 +21,7 @@ public function __construct(ResponseInterface $response, $httpBody, $previous = parent::__construct($this->message, $this->httpStatus, $previous); } - public function __toString() + public function __toString(): string { $base = 'Meilisearch InvalidResponseBodyException: Http Status: '.$this->httpStatus; diff --git a/src/Exceptions/TimeOutException.php b/src/Exceptions/TimeOutException.php index cf2c3a6e..b4da1656 100644 --- a/src/Exceptions/TimeOutException.php +++ b/src/Exceptions/TimeOutException.php @@ -17,13 +17,13 @@ public function __construct(?string $message = null, ?int $code = null, ?\Throwa parent::__construct($this->message, $this->code, $previous); } - public function __toString() + public function __toString(): string { $base = 'Meilisearch TimeOutException: Code: '.$this->code; if ('' !== $this->message) { return $base.' - Message: '.$this->message; - } else { - return $base; } + + return $base; } } diff --git a/src/Http/Serialize/Json.php b/src/Http/Serialize/Json.php index 0e66cdce..97ac79e6 100644 --- a/src/Http/Serialize/Json.php +++ b/src/Http/Serialize/Json.php @@ -6,12 +6,12 @@ class Json implements SerializerInterface { - public function serialize($data) + public function serialize(mixed $data): string|bool { return json_encode($data, JSON_THROW_ON_ERROR); } - public function unserialize(string $string) + public function unserialize(mixed $string): mixed { return json_decode($string, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR); } diff --git a/src/Http/Serialize/SerializerInterface.php b/src/Http/Serialize/SerializerInterface.php index 8e076019..c8d3861f 100644 --- a/src/Http/Serialize/SerializerInterface.php +++ b/src/Http/Serialize/SerializerInterface.php @@ -15,7 +15,7 @@ interface SerializerInterface * * @throws \JsonException */ - public function serialize($data); + public function serialize(mixed $data): string|bool; /** * Unserialize the given string. @@ -24,5 +24,5 @@ public function serialize($data); * * @throws \JsonException */ - public function unserialize(string $string); + public function unserialize(mixed $string): mixed; } diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 8715542b..912f2c71 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -8,7 +8,6 @@ use Meilisearch\Contracts\Http; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\ApiException; -use Meilisearch\Exceptions\InvalidArgumentException; use Meilisearch\Exceptions\InvalidResponseBodyException; use Meilisearch\Http\Client; use Psr\Http\Message\ResponseInterface; @@ -169,7 +168,6 @@ public function testGetSingleDocumentWithIntegerDocumentId(): void $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id']); - self::assertIsArray($response); self::assertSame($doc['id'], $response['id']); self::assertSame($doc['title'], $response['title']); } @@ -182,7 +180,6 @@ public function testGetSingleDocumentWithFields(): void $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id'], ['title']); - self::assertIsArray($response); self::assertSame($doc['title'], $response['title']); self::assertArrayNotHasKey('id', $response); } @@ -195,7 +192,6 @@ public function testGetSingleDocumentWithStringDocumentId(): void $index->waitForTask($addDocumentResponse['taskUid']); $response = $index->getDocument($stringDocumentId); - self::assertIsArray($response); self::assertSame($stringDocumentId, $response['id']); } @@ -378,23 +374,25 @@ public function testAddDocumentsCsvInBatchesWithDelimiter(): void $documentCsv .= '235115704;Mister Klein'.PHP_EOL; $index = $this - ->getMockBuilder('\Meilisearch\Endpoints\Indexes') + ->getMockBuilder(Indexes::class) ->onlyMethods(['addDocumentsCsv']) ->disableOriginalConstructor() ->getMock(); $index->expects(self::exactly(2)) ->method('addDocumentsCsv') - ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): void { + ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): array { static $invocation = 0; // withConsecutive has no replacement https://github.com/sebastianbergmann/phpunit/issues/4026 switch (++$invocation) { case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - break; + + return []; case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - break; + + return []; default: self::fail(); } @@ -896,23 +894,25 @@ public function testUpdateDocumentsCsvInBatchesWithDelimiter(): void $replacement .= '235115704;Mister Klein'.PHP_EOL; $index = $this - ->getMockBuilder('\Meilisearch\Endpoints\Indexes') + ->getMockBuilder(Indexes::class) ->onlyMethods(['updateDocumentsCsv']) ->disableOriginalConstructor() ->getMock(); $index->expects(self::atLeastOnce()) ->method('updateDocumentsCsv') - ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): void { + ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): array { static $invocation = 0; // withConsecutive has no replacement https://github.com/sebastianbergmann/phpunit/issues/4026 switch (++$invocation) { case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - break; + + return []; case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - break; + + return []; default: self::fail(); } @@ -951,41 +951,6 @@ public function testUpdateDocumentsNdjsonInBatches(): void self::assertSame('Ailitp', $response['artist']); } - /** - * @dataProvider invalidDocumentIds - */ - public function testFetchingDocumentWithInvalidId($documentId): void - { - $index = $this->createEmptyIndex($this->safeIndexName('movies-1')); - - $this->expectException(InvalidArgumentException::class); - $index->getDocument($documentId); - } - - /** - * @dataProvider invalidDocumentIds - */ - public function testDeletingDocumentWithInvalidId($documentId): void - { - $index = $this->createEmptyIndex($this->safeIndexName('movies-1')); - - $this->expectException(InvalidArgumentException::class); - $index->deleteDocument($documentId); - } - - public static function invalidDocumentIds(): array - { - return [ - 'documentId as null' => [null], - 'documentId as bool' => [true], - 'documentId as empty string' => [''], - 'documentId as float' => [2.1], - 'documentId as array' => [[]], - 'documentId as object' => [new \stdClass()], - 'documentId as resource' => [tmpfile()], - ]; - } - private function findDocumentWithId($documents, $documentId) { foreach ($documents as $document) { From b08c13e2a33bb1c73a49eee2281bb1d3d8172179 Mon Sep 17 00:00:00 2001 From: Tomas Date: Wed, 9 Apr 2025 15:17:20 +0300 Subject: [PATCH 03/51] Add task object and related enums --- src/Contracts/Task.php | 170 +++++++++++++++++++++++++++++++++++ src/Contracts/TaskStatus.php | 14 +++ src/Contracts/TaskType.php | 21 +++++ 3 files changed, 205 insertions(+) create mode 100644 src/Contracts/Task.php create mode 100644 src/Contracts/TaskStatus.php create mode 100644 src/Contracts/TaskType.php diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php new file mode 100644 index 00000000..d66d0509 --- /dev/null +++ b/src/Contracts/Task.php @@ -0,0 +1,170 @@ + $data Raw data + */ + public function __construct( + private readonly int $taskUid, + private readonly ?string $indexUid, + private readonly TaskStatus $status, + private readonly TaskType $type, + private readonly \DateTimeImmutable $enqueuedAt, + private readonly ?\DateTimeImmutable $startedAt = null, + private readonly ?\DateTimeImmutable $finishedAt = null, + private readonly ?string $duration = null, + private readonly ?int $canceledBy = null, + private readonly ?int $batchUid = null, + private readonly ?array $details = null, + private readonly ?array $error = null, + private readonly array $data = [], + ) { + } + + /** + * @return non-negative-int + */ + public function getTaskUid(): int + { + return $this->taskUid; + } + + /** + * @return non-empty-string|null + */ + public function getIndexUid(): ?string + { + return $this->indexUid; + } + + public function getStatus(): TaskStatus + { + return $this->status; + } + + public function getType(): TaskType + { + return $this->type; + } + + public function getEnqueuedAt(): \DateTimeImmutable + { + return $this->enqueuedAt; + } + + public function getStartedAt(): ?\DateTimeImmutable + { + return $this->startedAt; + } + + public function getFinishedAt(): ?\DateTimeImmutable + { + return $this->finishedAt; + } + + public function getDuration(): ?string + { + return $this->duration; + } + + public function getCanceledBy(): ?int + { + return $this->canceledBy; + } + + public function getBatchUid(): ?int + { + return $this->batchUid; + } + + public function getDetails(): ?array + { + return $this->details; + } + + public function getError(): ?array + { + return $this->error; + } + + /** + * @return array + */ + public function getData(): array + { + return $this->data; + } + + // @todo: deprecate + public function offsetExists(mixed $offset): bool + { + return \array_key_exists($offset, $this->data); + } + + // @todo: deprecate + public function offsetGet(mixed $offset): mixed + { + return $this->data[$offset] ?? null; + } + + // @todo: deprecate + public function offsetSet(mixed $offset, mixed $value): void + { + throw new \LogicException(\sprintf('Setting data on "%s::%s" is not supported.', get_debug_type($this), $offset)); + } + + // @todo: deprecate + public function offsetUnset(mixed $offset): void + { + throw new \LogicException(\sprintf('Unsetting data on "%s::%s" is not supported.', get_debug_type($this), $offset)); + } + + public function isFinished(): bool + { + return TaskStatus::Enqueued !== $this->status && TaskStatus::Processing !== $this->status; + } + + /** + * @param array{ + * taskUid?: int, + * uid?: int, + * indexUid: non-empty-string, + * status: non-empty-string, + * type: non-empty-string, + * enqueuedAt: non-empty-string, + * startedAt?: non-empty-string, + * finishedAt?: non-empty-string, + * duration?: non-empty-string, + * canceledBy?: int, + * batchUid?: int, + * details?: array, + * error?: array, + * data: array + * } $data + */ + public static function fromArray(array $data): Task + { + return new self( + $data['taskUid'] ?? $data['uid'], + $data['indexUid'], + TaskStatus::from($data['status']), + TaskType::from($data['type']), + new \DateTimeImmutable($data['enqueuedAt']), + isset($data['startedAt']) ? new \DateTimeImmutable($data['startedAt']) : null, + isset($data['finishedAt']) ? new \DateTimeImmutable($data['finishedAt']) : null, + $data['duration'] ?? null, + $data['canceledBy'] ?? null, + $data['batchUid'] ?? null, + $data['details'] ?? null, + $data['error'] ?? null, + $data, + ); + } +} diff --git a/src/Contracts/TaskStatus.php b/src/Contracts/TaskStatus.php new file mode 100644 index 00000000..b0e5e0ec --- /dev/null +++ b/src/Contracts/TaskStatus.php @@ -0,0 +1,14 @@ + Date: Wed, 9 Apr 2025 15:28:23 +0300 Subject: [PATCH 04/51] Replace task array return with Task object --- .php-cs-fixer.dist.php | 2 +- src/Contracts/Task.php | 16 +- src/Endpoints/Delegates/HandlesDocuments.php | 69 +++++--- src/Endpoints/Delegates/HandlesDumps.php | 3 +- src/Endpoints/Delegates/HandlesIndex.php | 7 +- src/Endpoints/Delegates/HandlesSettings.php | 165 ++++++++++--------- src/Endpoints/Delegates/HandlesSnapshots.php | 3 +- src/Endpoints/Delegates/HandlesSystem.php | 3 +- src/Endpoints/Delegates/HandlesTasks.php | 9 +- src/Endpoints/Dumps.php | 5 +- src/Endpoints/Indexes.php | 25 +-- src/Endpoints/Snapshots.php | 5 +- src/Endpoints/Tasks.php | 21 +-- tests/Contracts/TaskTest.php | 91 ++++++++++ tests/Endpoints/DocumentsTest.php | 53 +----- tests/Endpoints/DumpTest.php | 5 +- tests/Endpoints/IndexTest.php | 2 - tests/Endpoints/SearchTest.php | 3 +- tests/Endpoints/SnapshotsTest.php | 6 +- tests/Endpoints/TasksTest.php | 11 +- tests/MockTask.php | 22 +++ tests/Settings/DisplayedAttributesTest.php | 3 - tests/Settings/DistinctAttributeTest.php | 8 +- tests/Settings/EmbeddersTest.php | 11 +- tests/Settings/FacetSearchTest.php | 11 +- tests/Settings/FacetingAttributesTest.php | 11 +- tests/Settings/FilterableAttributesTest.php | 14 +- tests/Settings/LocalizedAttributesTest.php | 4 - tests/Settings/NonSeparatorTokensTest.php | 9 +- tests/Settings/PrefixSearchTest.php | 11 +- tests/Settings/ProximityPrecisionTest.php | 4 - tests/Settings/RankingRulesTest.php | 3 - tests/Settings/SearchCutoffMsTest.php | 4 - tests/Settings/SearchableAttributesTest.php | 13 +- tests/Settings/SeparatorTokensTest.php | 9 +- tests/Settings/SettingsTest.php | 11 +- tests/Settings/SortableAttributesTest.php | 16 +- tests/Settings/StopWordsTest.php | 11 +- tests/Settings/SynonymsTest.php | 19 +-- tests/Settings/TypoToleranceTest.php | 2 - tests/Settings/WordDictionaryTest.php | 13 +- 41 files changed, 359 insertions(+), 354 deletions(-) create mode 100644 tests/Contracts/TaskTest.php create mode 100644 tests/MockTask.php diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index c42da808..2bcdc65b 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -15,7 +15,7 @@ 'void_return' => true, 'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'], 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], - 'php_unit_strict' => true, + 'php_unit_strict' => false, 'trailing_comma_in_multiline' => ['after_heredoc' => true, 'elements' => ['array_destructuring', 'arrays', 'match', 'parameters']], ]) ->setRiskyAllowed(true) diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index d66d0509..cf262c54 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -9,7 +9,13 @@ final class Task implements \ArrayAccess /** * @param non-negative-int $taskUid * @param non-empty-string|null $indexUid - * @param array $data Raw data + * @param array{ + * message: non-empty-string, + * code: non-empty-string, + * type: non-empty-string, + * link: non-empty-string + * }|null $error + * @param array $data Raw data */ public function __construct( private readonly int $taskUid, @@ -89,6 +95,14 @@ public function getDetails(): ?array return $this->details; } + /** + * @return array{ + * message: non-empty-string, + * code: non-empty-string, + * type: non-empty-string, + * link: non-empty-string + * }|null + */ public function getError(): ?array { return $this->error; diff --git a/src/Endpoints/Delegates/HandlesDocuments.php b/src/Endpoints/Delegates/HandlesDocuments.php index 70eee739..b40a5cff 100644 --- a/src/Endpoints/Delegates/HandlesDocuments.php +++ b/src/Endpoints/Delegates/HandlesDocuments.php @@ -6,6 +6,7 @@ use Meilisearch\Contracts\DocumentsQuery; use Meilisearch\Contracts\DocumentsResults; +use MeiliSearch\Contracts\Task; use Meilisearch\Exceptions\ApiException; use Meilisearch\Exceptions\InvalidResponseBodyException; @@ -36,26 +37,29 @@ public function getDocuments(?DocumentsQuery $options = null): DocumentsResults } } - public function addDocuments(array $documents, ?string $primaryKey = null): array + public function addDocuments(array $documents, ?string $primaryKey = null): Task { - return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey]); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey])); } - public function addDocumentsJson(string $documents, ?string $primaryKey = null): array + public function addDocumentsJson(string $documents, ?string $primaryKey = null): Task { - return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json'); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json')); } - public function addDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): array + public function addDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): Task { - return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv'); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv')); } - public function addDocumentsNdjson(string $documents, ?string $primaryKey = null): array + public function addDocumentsNdjson(string $documents, ?string $primaryKey = null): Task { - return $this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson'); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson')); } + /** + * @return list + */ public function addDocumentsInBatches(array $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -67,6 +71,9 @@ public function addDocumentsInBatches(array $documents, ?int $batchSize = 1000, return $promises; } + /** + * @return list + */ public function addDocumentsCsvInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null, ?string $delimiter = null): array { $promises = []; @@ -78,6 +85,9 @@ public function addDocumentsCsvInBatches(string $documents, ?int $batchSize = 10 return $promises; } + /** + * @return list + */ public function addDocumentsNdjsonInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -89,26 +99,29 @@ public function addDocumentsNdjsonInBatches(string $documents, ?int $batchSize = return $promises; } - public function updateDocuments(array $documents, ?string $primaryKey = null): array + public function updateDocuments(array $documents, ?string $primaryKey = null): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey]); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey])); } - public function updateDocumentsJson(string $documents, ?string $primaryKey = null): array + public function updateDocumentsJson(string $documents, ?string $primaryKey = null): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json'); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json')); } - public function updateDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): array + public function updateDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv'); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv')); } - public function updateDocumentsNdjson(string $documents, ?string $primaryKey = null): array + public function updateDocumentsNdjson(string $documents, ?string $primaryKey = null): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson'); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson')); } + /** + * @return list + */ public function updateDocumentsInBatches(array $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -120,6 +133,9 @@ public function updateDocumentsInBatches(array $documents, ?int $batchSize = 100 return $promises; } + /** + * @return list + */ public function updateDocumentsCsvInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null, ?string $delimiter = null): array { $promises = []; @@ -131,6 +147,9 @@ public function updateDocumentsCsvInBatches(string $documents, ?int $batchSize = return $promises; } + /** + * @return list + */ public function updateDocumentsNdjsonInBatches(string $documents, ?int $batchSize = 1000, ?string $primaryKey = null): array { $promises = []; @@ -152,31 +171,31 @@ public function updateDocumentsNdjsonInBatches(string $documents, ?int $batchSiz * @param non-empty-string $function * @param array{filter?: non-empty-string|list|null, context?: array} $options */ - public function updateDocumentsByFunction(string $function, array $options = []): array + public function updateDocumentsByFunction(string $function, array $options = []): Task { - return $this->http->post(self::PATH.'/'.$this->uid.'/documents/edit', array_merge(['function' => $function], $options)); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/edit', array_merge(['function' => $function], $options))); } - public function deleteAllDocuments(): array + public function deleteAllDocuments(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/documents'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/documents')); } - public function deleteDocument(string|int $documentId): array + public function deleteDocument(string|int $documentId): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/documents/'.$documentId); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/documents/'.$documentId)); } - public function deleteDocuments(array $options): array + public function deleteDocuments(array $options): Task { try { if (\array_key_exists('filter', $options) && $options['filter']) { - return $this->http->post(self::PATH.'/'.$this->uid.'/documents/delete', $options); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/delete', $options)); } // backwards compatibility: // expect to be a array to send alongside as $documents_ids. - return $this->http->post(self::PATH.'/'.$this->uid.'/documents/delete-batch', $options); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/delete-batch', $options)); } catch (InvalidResponseBodyException $e) { throw ApiException::rethrowWithHint($e, __FUNCTION__); } diff --git a/src/Endpoints/Delegates/HandlesDumps.php b/src/Endpoints/Delegates/HandlesDumps.php index 7e73f87e..6d8eb659 100644 --- a/src/Endpoints/Delegates/HandlesDumps.php +++ b/src/Endpoints/Delegates/HandlesDumps.php @@ -4,13 +4,14 @@ namespace Meilisearch\Endpoints\Delegates; +use MeiliSearch\Contracts\Task; use Meilisearch\Endpoints\Dumps; trait HandlesDumps { protected Dumps $dumps; - public function createDump(): array + public function createDump(): Task { return $this->dumps->create(); } diff --git a/src/Endpoints/Delegates/HandlesIndex.php b/src/Endpoints/Delegates/HandlesIndex.php index 75b84e63..1e1f0a1b 100644 --- a/src/Endpoints/Delegates/HandlesIndex.php +++ b/src/Endpoints/Delegates/HandlesIndex.php @@ -6,6 +6,7 @@ use Meilisearch\Contracts\IndexesQuery; use Meilisearch\Contracts\IndexesResults; +use MeiliSearch\Contracts\Task; use Meilisearch\Endpoints\Indexes; trait HandlesIndex @@ -44,7 +45,7 @@ public function getIndex(string $uid): Indexes /** * @param non-empty-string $uid */ - public function deleteIndex(string $uid): array + public function deleteIndex(string $uid): Task { return $this->index($uid)->delete(); } @@ -52,7 +53,7 @@ public function deleteIndex(string $uid): array /** * @param non-empty-string $uid */ - public function createIndex(string $uid, array $options = []): array + public function createIndex(string $uid, array $options = []): Task { return $this->index->create($uid, $options); } @@ -60,7 +61,7 @@ public function createIndex(string $uid, array $options = []): array /** * @param non-empty-string $uid */ - public function updateIndex(string $uid, array $options = []): array + public function updateIndex(string $uid, array $options = []): Task { return $this->index($uid)->update($options); } diff --git a/src/Endpoints/Delegates/HandlesSettings.php b/src/Endpoints/Delegates/HandlesSettings.php index 203e84af..7cfa82f6 100644 --- a/src/Endpoints/Delegates/HandlesSettings.php +++ b/src/Endpoints/Delegates/HandlesSettings.php @@ -7,6 +7,7 @@ use Meilisearch\Contracts\Index\Faceting; use Meilisearch\Contracts\Index\Synonyms; use Meilisearch\Contracts\Index\TypoTolerance; +use MeiliSearch\Contracts\Task; trait HandlesSettings { @@ -23,14 +24,14 @@ public function getRankingRules(): array /** * @param list $rankingRules */ - public function updateRankingRules(array $rankingRules): array + public function updateRankingRules(array $rankingRules): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/ranking-rules', $rankingRules); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/ranking-rules', $rankingRules)); } - public function resetRankingRules(): array + public function resetRankingRules(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/ranking-rules'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/ranking-rules')); } // Settings - Distinct attribute @@ -46,14 +47,14 @@ public function getDistinctAttribute(): ?string /** * @param non-empty-string $distinctAttribute */ - public function updateDistinctAttribute(string $distinctAttribute): array + public function updateDistinctAttribute(string $distinctAttribute): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/distinct-attribute', $distinctAttribute); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/distinct-attribute', $distinctAttribute)); } - public function resetDistinctAttribute(): array + public function resetDistinctAttribute(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/distinct-attribute'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/distinct-attribute')); } // Settings - Searchable attributes @@ -69,14 +70,14 @@ public function getSearchableAttributes(): array /** * @param list $searchableAttributes */ - public function updateSearchableAttributes(array $searchableAttributes): array + public function updateSearchableAttributes(array $searchableAttributes): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/searchable-attributes', $searchableAttributes); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/searchable-attributes', $searchableAttributes)); } - public function resetSearchableAttributes(): array + public function resetSearchableAttributes(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/searchable-attributes'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/searchable-attributes')); } // Settings - Displayed attributes @@ -92,14 +93,14 @@ public function getDisplayedAttributes(): array /** * @param list $displayedAttributes */ - public function updateDisplayedAttributes(array $displayedAttributes): array + public function updateDisplayedAttributes(array $displayedAttributes): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/displayed-attributes', $displayedAttributes); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/displayed-attributes', $displayedAttributes)); } - public function resetDisplayedAttributes(): array + public function resetDisplayedAttributes(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/displayed-attributes'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/displayed-attributes')); } // Settings - Localized attributes @@ -115,14 +116,14 @@ public function getLocalizedAttributes(): ?array /** * @param list, locales: list}> $localizedAttributes */ - public function updateLocalizedAttributes(array $localizedAttributes): array + public function updateLocalizedAttributes(array $localizedAttributes): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/localized-attributes', $localizedAttributes); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/localized-attributes', $localizedAttributes)); } - public function resetLocalizedAttributes(): array + public function resetLocalizedAttributes(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/localized-attributes'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/localized-attributes')); } // Settings - Faceting @@ -139,14 +140,14 @@ public function getFaceting(): array /** * @param array{maxValuesPerFacet?: int, sortFacetValuesBy?: array} $faceting */ - public function updateFaceting(array $faceting): array + public function updateFaceting(array $faceting): Task { - return $this->http->patch(self::PATH.'/'.$this->uid.'/settings/faceting', $faceting); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/faceting', $faceting)); } - public function resetFaceting(): array + public function resetFaceting(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/faceting'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/faceting')); } // Settings - Pagination @@ -162,14 +163,14 @@ public function getPagination(): array /** * @param array{maxTotalHits: positive-int} $pagination */ - public function updatePagination(array $pagination): array + public function updatePagination(array $pagination): Task { - return $this->http->patch(self::PATH.'/'.$this->uid.'/settings/pagination', $pagination); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/pagination', $pagination)); } - public function resetPagination(): array + public function resetPagination(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/pagination'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/pagination')); } // Settings - Stop-words @@ -185,14 +186,14 @@ public function getStopWords(): array /** * @param list $stopWords */ - public function updateStopWords(array $stopWords): array + public function updateStopWords(array $stopWords): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/stop-words', $stopWords); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/stop-words', $stopWords)); } - public function resetStopWords(): array + public function resetStopWords(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/stop-words'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/stop-words')); } // Settings - Synonyms @@ -209,14 +210,14 @@ public function getSynonyms(): array /** * @param array> $synonyms */ - public function updateSynonyms(array $synonyms): array + public function updateSynonyms(array $synonyms): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/synonyms', new Synonyms($synonyms)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/synonyms', new Synonyms($synonyms))); } - public function resetSynonyms(): array + public function resetSynonyms(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/synonyms'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/synonyms')); } // Settings - Filterable Attributes @@ -243,14 +244,14 @@ public function getFilterableAttributes(): array * * Note: When attributePatterns contains '_geo', the features field is ignored */ - public function updateFilterableAttributes(array $filterableAttributes): array + public function updateFilterableAttributes(array $filterableAttributes): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/filterable-attributes', $filterableAttributes); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/filterable-attributes', $filterableAttributes)); } - public function resetFilterableAttributes(): array + public function resetFilterableAttributes(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/filterable-attributes'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/filterable-attributes')); } // Settings - Sortable Attributes @@ -266,14 +267,14 @@ public function getSortableAttributes(): array /** * @param list $sortableAttributes */ - public function updateSortableAttributes(array $sortableAttributes): array + public function updateSortableAttributes(array $sortableAttributes): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/sortable-attributes', $sortableAttributes); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/sortable-attributes', $sortableAttributes)); } - public function resetSortableAttributes(): array + public function resetSortableAttributes(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/sortable-attributes'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/sortable-attributes')); } // Settings - Typo Tolerance @@ -302,14 +303,14 @@ public function getTypoTolerance(): array * disableOnNumbers: bool * } $typoTolerance */ - public function updateTypoTolerance(array $typoTolerance): array + public function updateTypoTolerance(array $typoTolerance): Task { - return $this->http->patch(self::PATH.'/'.$this->uid.'/settings/typo-tolerance', new TypoTolerance($typoTolerance)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/typo-tolerance', new TypoTolerance($typoTolerance))); } - public function resetTypoTolerance(): array + public function resetTypoTolerance(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/typo-tolerance'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/typo-tolerance')); } // Settings - Word dictionary @@ -325,14 +326,14 @@ public function getDictionary(): array /** * @param list $wordDictionary */ - public function updateDictionary(array $wordDictionary): array + public function updateDictionary(array $wordDictionary): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/dictionary', $wordDictionary); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/dictionary', $wordDictionary)); } - public function resetDictionary(): array + public function resetDictionary(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/dictionary'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/dictionary')); } // Settings - Separator tokens @@ -345,14 +346,14 @@ public function getSeparatorTokens(): array /** * @param list $separatorTokens */ - public function updateSeparatorTokens(array $separatorTokens): array + public function updateSeparatorTokens(array $separatorTokens): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/separator-tokens', $separatorTokens); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/separator-tokens', $separatorTokens)); } - public function resetSeparatorTokens(): array + public function resetSeparatorTokens(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/separator-tokens'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/separator-tokens')); } // Settings - Non-Separator tokens @@ -368,14 +369,14 @@ public function getNonSeparatorTokens(): array /** * @param list $nonSeparatorTokens */ - public function updateNonSeparatorTokens(array $nonSeparatorTokens): array + public function updateNonSeparatorTokens(array $nonSeparatorTokens): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens', $nonSeparatorTokens); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens', $nonSeparatorTokens)); } - public function resetNonSeparatorTokens(): array + public function resetNonSeparatorTokens(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens')); } // Settings - proximityPrecision @@ -391,14 +392,14 @@ public function getProximityPrecision(): string /** * @param 'byWord'|'byAttribute' $type */ - public function updateProximityPrecision(string $type): array + public function updateProximityPrecision(string $type): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/proximity-precision', $type); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/proximity-precision', $type)); } - public function resetProximityPrecision(): array + public function resetProximityPrecision(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/proximity-precision'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/proximity-precision')); } // Settings - searchCutoffMs @@ -408,14 +409,14 @@ public function getSearchCutoffMs(): ?int return $this->http->get(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms'); } - public function updateSearchCutoffMs(int $value): array + public function updateSearchCutoffMs(int $value): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms', $value); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms', $value)); } - public function resetSearchCutoffMs(): array + public function resetSearchCutoffMs(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms')); } // Settings - Embedders @@ -431,17 +432,17 @@ public function getEmbedders(): ?array /** * @since Meilisearch v1.13.0 */ - public function updateEmbedders(array $embedders): array + public function updateEmbedders(array $embedders): Task { - return $this->http->patch(self::PATH.'/'.$this->uid.'/settings/embedders', $embedders); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/embedders', $embedders)); } /** * @since Meilisearch v1.13.0 */ - public function resetEmbedders(): array + public function resetEmbedders(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/embedders'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/embedders')); } // Settings - Facet Search @@ -457,17 +458,17 @@ public function getFacetSearch(): bool /** * @since Meilisearch v1.12.0 */ - public function updateFacetSearch(bool $facetSearch): array + public function updateFacetSearch(bool $facetSearch): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/facet-search', $facetSearch); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/facet-search', $facetSearch)); } /** * @since Meilisearch v1.12.0 */ - public function resetFacetSearch(): array + public function resetFacetSearch(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/facet-search'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/facet-search')); } // Settings - Prefix Search @@ -487,17 +488,17 @@ public function getPrefixSearch(): string * * @since Meilisearch v1.12.0 */ - public function updatePrefixSearch(string $prefixSearch): array + public function updatePrefixSearch(string $prefixSearch): Task { - return $this->http->put(self::PATH.'/'.$this->uid.'/settings/prefix-search', $prefixSearch); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/prefix-search', $prefixSearch)); } /** * @since Meilisearch v1.12.0 */ - public function resetPrefixSearch(): array + public function resetPrefixSearch(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings/prefix-search'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/prefix-search')); } // Settings - Chat @@ -583,8 +584,8 @@ public function getChat(): array * } * } $chatSettings */ - public function updateChat(array $chatSettings): array + public function updateChat(array $chatSettings): Task { - return $this->http->patch(self::PATH.'/'.$this->uid.'/settings/chat', $chatSettings); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/chat', $chatSettings)); } } diff --git a/src/Endpoints/Delegates/HandlesSnapshots.php b/src/Endpoints/Delegates/HandlesSnapshots.php index c8082a76..6e5567bf 100644 --- a/src/Endpoints/Delegates/HandlesSnapshots.php +++ b/src/Endpoints/Delegates/HandlesSnapshots.php @@ -4,13 +4,14 @@ namespace Meilisearch\Endpoints\Delegates; +use MeiliSearch\Contracts\Task; use Meilisearch\Endpoints\Snapshots; trait HandlesSnapshots { protected Snapshots $snapshots; - public function createSnapshot(): array + public function createSnapshot(): Task { return $this->snapshots->create(); } diff --git a/src/Endpoints/Delegates/HandlesSystem.php b/src/Endpoints/Delegates/HandlesSystem.php index 7abb2937..93692c2c 100644 --- a/src/Endpoints/Delegates/HandlesSystem.php +++ b/src/Endpoints/Delegates/HandlesSystem.php @@ -4,6 +4,7 @@ namespace Meilisearch\Endpoints\Delegates; +use MeiliSearch\Contracts\Task; use Meilisearch\Endpoints\Health; use Meilisearch\Endpoints\Stats; use Meilisearch\Endpoints\TenantToken; @@ -47,7 +48,7 @@ public function generateTenantToken(string $apiKeyUid, $searchRules, array $opti return $this->tenantToken->generateTenantToken($apiKeyUid, $searchRules, $options); } - public function swapIndexes(array $indexes): array + public function swapIndexes(array $indexes): Task { $options = array_map(static fn ($data) => ['indexes' => $data], $indexes); diff --git a/src/Endpoints/Delegates/HandlesTasks.php b/src/Endpoints/Delegates/HandlesTasks.php index 96e108cb..1b386020 100644 --- a/src/Endpoints/Delegates/HandlesTasks.php +++ b/src/Endpoints/Delegates/HandlesTasks.php @@ -6,6 +6,7 @@ use Meilisearch\Contracts\CancelTasksQuery; use Meilisearch\Contracts\DeleteTasksQuery; +use MeiliSearch\Contracts\Task; use Meilisearch\Contracts\TasksQuery; use Meilisearch\Contracts\TasksResults; use Meilisearch\Endpoints\Tasks; @@ -15,7 +16,7 @@ trait HandlesTasks { protected Tasks $tasks; - public function getTask(int $uid): array + public function getTask(int $uid): Task { return $this->tasks->get($uid); } @@ -29,12 +30,12 @@ public function getTasks(?TasksQuery $options = null): TasksResults return new TasksResults($response); } - public function deleteTasks(?DeleteTasksQuery $options = null): array + public function deleteTasks(?DeleteTasksQuery $options = null): Task { return $this->tasks->deleteTasks($options); } - public function cancelTasks(?CancelTasksQuery $options = null): array + public function cancelTasks(?CancelTasksQuery $options = null): Task { return $this->tasks->cancelTasks($options); } @@ -42,7 +43,7 @@ public function cancelTasks(?CancelTasksQuery $options = null): array /** * @throws TimeOutException */ - public function waitForTask(int $uid, int $timeoutInMs = 5000, int $intervalInMs = 50): array + public function waitForTask(int $uid, int $timeoutInMs = 5000, int $intervalInMs = 50): Task { return $this->tasks->waitTask($uid, $timeoutInMs, $intervalInMs); } diff --git a/src/Endpoints/Dumps.php b/src/Endpoints/Dumps.php index 1d662896..d6edb3bf 100644 --- a/src/Endpoints/Dumps.php +++ b/src/Endpoints/Dumps.php @@ -5,13 +5,14 @@ namespace Meilisearch\Endpoints; use Meilisearch\Contracts\Endpoint; +use MeiliSearch\Contracts\Task; class Dumps extends Endpoint { protected const PATH = '/dumps'; - public function create(): array + public function create(): Task { - return $this->http->post(self::PATH); + return Task::fromArray($this->http->post(self::PATH)); } } diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index e4a020ca..989fdd51 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -11,6 +11,7 @@ use Meilisearch\Contracts\IndexesQuery; use Meilisearch\Contracts\IndexesResults; use Meilisearch\Contracts\SimilarDocumentsQuery; +use MeiliSearch\Contracts\Task; use Meilisearch\Contracts\TasksQuery; use Meilisearch\Contracts\TasksResults; use Meilisearch\Endpoints\Delegates\HandlesDocuments; @@ -72,11 +73,11 @@ protected function fill(array $attributes): self /** * @throws \Exception|ApiException */ - public function create(string $uid, array $options = []): array + public function create(string $uid, array $options = []): Task { $options['uid'] = $uid; - return $this->http->post(self::PATH, $options); + return Task::fromArray($this->http->post(self::PATH, $options)); } public function all(?IndexesQuery $options = null): IndexesResults @@ -136,22 +137,22 @@ public function fetchInfo(): self return $this->fill($response); } - public function update(array $body): array + public function update(array $body): Task { - return $this->http->patch(self::PATH.'/'.$this->uid, $body); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid, $body)); } - public function delete(): array + public function delete(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid) ?? []; + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid) ?? []); } /** * @param array $indexes */ - public function swapIndexes(array $indexes): array + public function swapIndexes(array $indexes): Task { - return $this->http->post('/swap-indexes', $indexes); + return Task::fromArray($this->http->post('/swap-indexes', $indexes)); } // Tasks @@ -244,14 +245,14 @@ public function getSettings(): array ->getIterator()->getArrayCopy(); } - public function updateSettings($settings): array + public function updateSettings($settings): Task { - return $this->http->patch(self::PATH.'/'.$this->uid.'/settings', $settings); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings', $settings)); } - public function resetSettings(): array + public function resetSettings(): Task { - return $this->http->delete(self::PATH.'/'.$this->uid.'/settings'); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings')); } /** diff --git a/src/Endpoints/Snapshots.php b/src/Endpoints/Snapshots.php index fa559176..dd99a3d7 100644 --- a/src/Endpoints/Snapshots.php +++ b/src/Endpoints/Snapshots.php @@ -5,13 +5,14 @@ namespace Meilisearch\Endpoints; use Meilisearch\Contracts\Endpoint; +use MeiliSearch\Contracts\Task; class Snapshots extends Endpoint { protected const PATH = '/snapshots'; - public function create(): array + public function create(): Task { - return $this->http->post(self::PATH); + return Task::fromArray($this->http->post(self::PATH)); } } diff --git a/src/Endpoints/Tasks.php b/src/Endpoints/Tasks.php index b80f3481..8e6f42f7 100644 --- a/src/Endpoints/Tasks.php +++ b/src/Endpoints/Tasks.php @@ -7,15 +7,16 @@ use Meilisearch\Contracts\CancelTasksQuery; use Meilisearch\Contracts\DeleteTasksQuery; use Meilisearch\Contracts\Endpoint; +use MeiliSearch\Contracts\Task; use Meilisearch\Exceptions\TimeOutException; class Tasks extends Endpoint { protected const PATH = '/tasks'; - public function get(int $taskUid): array + public function get(int $taskUid): Task { - return $this->http->get(self::PATH.'/'.$taskUid); + return Task::fromArray($this->http->get(self::PATH.'/'.$taskUid)); } public function all(array $query = []): array @@ -23,32 +24,32 @@ public function all(array $query = []): array return $this->http->get(self::PATH.'/', $query); } - public function cancelTasks(?CancelTasksQuery $options): array + public function cancelTasks(?CancelTasksQuery $options): Task { $options = $options ?? new CancelTasksQuery(); - return $this->http->post('/tasks/cancel', null, $options->toArray()); + return Task::fromArray($this->http->post('/tasks/cancel', null, $options->toArray())); } - public function deleteTasks(?DeleteTasksQuery $options): array + public function deleteTasks(?DeleteTasksQuery $options): Task { $options = $options ?? new DeleteTasksQuery(); - return $this->http->delete(self::PATH, $options->toArray()); + return Task::fromArray($this->http->delete(self::PATH, $options->toArray())); } /** * @throws TimeOutException */ - public function waitTask(int $taskUid, int $timeoutInMs, int $intervalInMs): array + public function waitTask(int $taskUid, int $timeoutInMs, int $intervalInMs): Task { $timeoutTemp = 0; while ($timeoutInMs > $timeoutTemp) { - $res = $this->get($taskUid); + $task = $this->get($taskUid); - if ('enqueued' !== $res['status'] && 'processing' !== $res['status']) { - return $res; + if ($task->isFinished()) { + return $task; } $timeoutTemp += $intervalInMs; diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php new file mode 100644 index 00000000..6e29fdac --- /dev/null +++ b/tests/Contracts/TaskTest.php @@ -0,0 +1,91 @@ + 'detail'], + error: [ + 'message' => 'Index `documents` not found.', + 'code' => 'index_not_found', + 'type' => 'invalid_request', + 'link' => 'https://docs.meilisearch.com/errors#index_not_found', + ], + data: [ + 'taskUid' => 1, + 'indexUid' => 'documents', + 'status' => 'failed', + 'type' => 'index_creation', + 'enqueuedAt' => '2025-04-09T10:28:12.236789123Z', + ], + ); + + self::assertSame(1, $task->getTaskUid()); + self::assertSame('documents', $task->getIndexUid()); + self::assertSame(TaskStatus::Failed, $task->getStatus()); + self::assertSame(TaskType::IndexCreation, $task->getType()); + self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.236789'), $task->getEnqueuedAt()); + self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.555566+0000'), $task->getStartedAt()); + self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.666677+0000'), $task->getFinishedAt()); + self::assertSame('PT0.184408715S', $task->getDuration()); + self::assertSame(123, $task->getCanceledBy()); + self::assertSame(666, $task->getBatchUid()); + self::assertSame(['some' => 'detail'], $task->getDetails()); + self::assertSame([ + 'message' => 'Index `documents` not found.', + 'code' => 'index_not_found', + 'type' => 'invalid_request', + 'link' => 'https://docs.meilisearch.com/errors#index_not_found', + ], $task->getError()); + + self::assertSame(1, $task['taskUid']); + self::assertSame('documents', $task['indexUid']); + self::assertSame('failed', $task['status']); + self::assertSame('index_creation', $task['type']); + self::assertSame('2025-04-09T10:28:12.236789123Z', $task['enqueuedAt']); + } + + public function testCreateEnqueuedTask(): void + { + $task = new Task( + taskUid: 1, + indexUid: 'documents', + status: TaskStatus::Enqueued, + type: TaskType::IndexCreation, + enqueuedAt: new \DateTimeImmutable('2025-04-09 10:28:12.236789'), + ); + + self::assertSame(1, $task->getTaskUid()); + self::assertSame('documents', $task->getIndexUid()); + self::assertSame(TaskStatus::Enqueued, $task->getStatus()); + self::assertSame(TaskType::IndexCreation, $task->getType()); + self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.236789+0000'), $task->getEnqueuedAt()); + self::assertNull($task->getStartedAt()); + self::assertNull($task->getFinishedAt()); + self::assertNull($task->getDuration()); + self::assertNull($task->getCanceledBy()); + self::assertNull($task->getBatchUid()); + self::assertNull($task->getDetails()); + self::assertNull($task->getError()); + } +} diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 912f2c71..1d9e4fac 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -6,11 +6,14 @@ use Meilisearch\Contracts\DocumentsQuery; use Meilisearch\Contracts\Http; +use MeiliSearch\Contracts\Task; +use MeiliSearch\Contracts\TaskType; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\ApiException; use Meilisearch\Exceptions\InvalidResponseBodyException; use Meilisearch\Http\Client; use Psr\Http\Message\ResponseInterface; +use Tests\MockTask; use Tests\TestCase; final class DocumentsTest extends TestCase @@ -20,8 +23,6 @@ public function testAddDocuments(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $promise = $index->addDocuments(self::DOCUMENTS); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); @@ -35,7 +36,6 @@ public function testAddDocumentsInBatches(): void self::assertCount(4, $promises); foreach ($promises as $promise) { - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); } @@ -54,7 +54,6 @@ public function testAddDocumentWithSpecialChars(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $promise = $index->addDocuments($documents); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); @@ -76,8 +75,6 @@ public function testAddDocumentsCsv(): void $promise = $index->addDocumentsCsv($documentCsv); - $this->assertIsValidPromise($promise); - $update = $index->waitForTask($promise['taskUid']); self::assertSame('succeeded', $update['status']); @@ -95,8 +92,6 @@ public function testAddDocumentsCsvWithCustomSeparator(): void $promise = $index->addDocumentsCsv($csv, null, '|'); - $this->assertIsValidPromise($promise); - $update = $index->waitForTask($promise['taskUid']); self::assertSame('succeeded', $update['status']); @@ -117,8 +112,6 @@ public function testAddDocumentsJson(): void $promise = $index->addDocumentsJson($documentJson); - $this->assertIsValidPromise($promise); - $update = $index->waitForTask($promise['taskUid']); self::assertSame('succeeded', $update['status']); @@ -138,8 +131,6 @@ public function testAddDocumentsNdJson(): void $promise = $index->addDocumentsNdjson($documentNdJson); - $this->assertIsValidPromise($promise); - $update = $index->waitForTask($promise['taskUid']); self::assertSame('succeeded', $update['status']); @@ -220,8 +211,6 @@ public function testReplaceDocuments(): void ]; $response = $index->addDocuments([$replacement]); - $this->assertIsValidPromise($response); - $index->waitForTask($response['taskUid']); $response = $index->getDocument($replacement['id']); @@ -243,8 +232,6 @@ public function testUpdateDocuments(): void ]; $promise = $index->updateDocuments([$replacement]); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocument($replacement['id']); @@ -275,7 +262,6 @@ public function testUpdateDocumentsInBatches(): void self::assertCount(2, $promises); foreach ($promises as $promise) { - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); } @@ -359,7 +345,6 @@ public function testAddDocumentsCsvInBatches(): void self::assertCount(2, $promises); foreach ($promises as $promise) { - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); } @@ -381,18 +366,18 @@ public function testAddDocumentsCsvInBatchesWithDelimiter(): void $index->expects(self::exactly(2)) ->method('addDocumentsCsv') - ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): array { + ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): Task { static $invocation = 0; // withConsecutive has no replacement https://github.com/sebastianbergmann/phpunit/issues/4026 switch (++$invocation) { case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - return []; + return MockTask::create(TaskType::DocumentEdition); case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - return []; + return MockTask::create(TaskType::DocumentEdition); default: self::fail(); } @@ -416,7 +401,6 @@ public function testAddDocumentsNdjsonInBatches(): void self::assertCount(2, $promises); foreach ($promises as $promise) { - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); } @@ -435,8 +419,6 @@ public function testAddWithUpdateDocuments(): void ]; $promise = $index->updateDocuments([$document]); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocument($document['id']); @@ -458,8 +440,6 @@ public function testDeleteNonExistingDocument(): void $documentId = 9; $promise = $index->deleteDocument($documentId); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); @@ -476,8 +456,6 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsInteger(): void $documentId = 123; $promise = $index->deleteDocument($documentId); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); @@ -508,8 +486,6 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsInteger(): void $documentIds = [1, 2]; $promise = $index->deleteDocuments($documentIds); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); @@ -527,8 +503,6 @@ public function testDeleteMultipleDocumentsWithFilter(): void $filter = ['filter' => ['id > 0']]; $promise = $index->deleteDocuments($filter); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); @@ -583,8 +557,6 @@ public function testDeleteAllDocuments(): void $index->waitForTask($response['taskUid']); $promise = $index->deleteAllDocuments(); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(); @@ -631,8 +603,6 @@ public function testUpdateDocumentWithPrimaryKey(): void $index = $this->createEmptyIndex($this->safeIndexName()); $promise = $index->updateDocuments($documents, 'unique'); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); self::assertSame('unique', $index->fetchPrimaryKey()); @@ -643,7 +613,6 @@ public function testGetDocumentsWithPagination(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); $promise = $index->addDocuments(self::DOCUMENTS); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $response = $index->getDocuments((new DocumentsQuery())->setLimit(3)); @@ -712,10 +681,8 @@ public function testGetDocumentsWithVector(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $promise = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $promise = $index->updateDocuments(self::VECTOR_MOVIES); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $response = $index->getDocuments(new DocumentsQuery()); @@ -874,7 +841,6 @@ public function testUpdateDocumentsCsvInBatches(): void $promises = $index->updateDocumentsCsvInBatches($replacement, 1); self::assertCount(2, $promises); foreach ($promises as $promise) { - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); } @@ -901,18 +867,18 @@ public function testUpdateDocumentsCsvInBatchesWithDelimiter(): void $index->expects(self::atLeastOnce()) ->method('updateDocumentsCsv') - ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): array { + ->willReturnCallback(function (string $documents, $primaryKey, $delimiter): Task { static $invocation = 0; // withConsecutive has no replacement https://github.com/sebastianbergmann/phpunit/issues/4026 switch (++$invocation) { case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - return []; + return MockTask::create(TaskType::DocumentEdition); case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - return []; + return MockTask::create(TaskType::DocumentEdition); default: self::fail(); } @@ -938,7 +904,6 @@ public function testUpdateDocumentsNdjsonInBatches(): void $promises = $index->updateDocumentsNdjsonInBatches($replacement, 1); self::assertCount(2, $promises); foreach ($promises as $promise) { - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); } diff --git a/tests/Endpoints/DumpTest.php b/tests/Endpoints/DumpTest.php index ee18ff7c..fa17d4b2 100644 --- a/tests/Endpoints/DumpTest.php +++ b/tests/Endpoints/DumpTest.php @@ -4,16 +4,15 @@ namespace Tests\Endpoints; +use MeiliSearch\Contracts\TaskType; use Tests\TestCase; final class DumpTest extends TestCase { public function testCreateDump(): void { - $expectedKeys = ['taskUid', 'indexUid', 'status', 'type', 'enqueuedAt']; - $task = $this->client->createDump(); - self::assertSame($expectedKeys, array_keys($task)); + self::assertSame(TaskType::DumpCreation, $task->getType()); } } diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 550a66b3..40c0691f 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -189,8 +189,6 @@ public function testWaitForTaskDefault(): void $response = $this->index->waitForTask($promise['taskUid']); - /* @phpstan-ignore-next-line */ - self::assertIsArray($response); self::assertSame('succeeded', $response['status']); self::assertSame($response['uid'], $promise['taskUid']); self::assertArrayHasKey('type', $response); diff --git a/tests/Endpoints/SearchTest.php b/tests/Endpoints/SearchTest.php index 258a12a6..4e131543 100644 --- a/tests/Endpoints/SearchTest.php +++ b/tests/Endpoints/SearchTest.php @@ -710,10 +710,9 @@ public function testVectorSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $promise = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); + $promise = $index->updateDocuments(self::VECTOR_MOVIES); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $response = $index->search('', ['vector' => [-0.5, 0.3, 0.85], 'hybrid' => ['semanticRatio' => 1.0, 'embedder' => 'manual']]); diff --git a/tests/Endpoints/SnapshotsTest.php b/tests/Endpoints/SnapshotsTest.php index 509100af..8a1cad9f 100644 --- a/tests/Endpoints/SnapshotsTest.php +++ b/tests/Endpoints/SnapshotsTest.php @@ -4,17 +4,15 @@ namespace Tests\Endpoints; +use MeiliSearch\Contracts\TaskType; use Tests\TestCase; final class SnapshotsTest extends TestCase { public function testCreateSnapshots(): void { - $expectedKeys = ['taskUid', 'indexUid', 'status', 'type', 'enqueuedAt']; - $task = $this->client->createSnapshot(); - self::assertSame($expectedKeys, array_keys($task)); - self::assertSame('snapshotCreation', $task['type']); + self::assertSame(TaskType::SnapshotCreation, $task->getType()); } } diff --git a/tests/Endpoints/TasksTest.php b/tests/Endpoints/TasksTest.php index 49bf8fa3..513f632e 100644 --- a/tests/Endpoints/TasksTest.php +++ b/tests/Endpoints/TasksTest.php @@ -26,7 +26,6 @@ public function testGetOneTaskFromWaitTask(): void { [$promise, $response] = $this->seedIndex(); - self::assertIsArray($response); self::assertArrayHasKey('status', $response); self::assertSame($response['uid'], $promise['taskUid']); self::assertArrayHasKey('type', $response); @@ -41,9 +40,8 @@ public function testGetOneTaskFromWaitTask(): void public function testGetOneTaskClient(): void { - [$promise, $response] = $this->seedIndex(); + [$promise] = $this->seedIndex(); - self::assertIsArray($promise); $response = $this->client->getTask($promise['taskUid']); self::assertArrayHasKey('status', $response); self::assertSame($response['uid'], $promise['taskUid']); @@ -78,7 +76,7 @@ public function testGetAllTasksClientWithPagination(): void public function getAllTasksClientWithBatchFilter(): void { - [$promise, $response] = $this->seedIndex(); + [$promise] = $this->seedIndex(); $task = $this->client->getTask($promise['taskUid']); $response = $this->client->getTasks((new TasksQuery()) @@ -90,9 +88,8 @@ public function getAllTasksClientWithBatchFilter(): void public function testGetOneTaskIndex(): void { - [$promise, $response] = $this->seedIndex(); + [$promise] = $this->seedIndex(); - self::assertIsArray($promise); $response = $this->index->getTask($promise['taskUid']); self::assertArrayHasKey('status', $response); self::assertSame($response['uid'], $promise['taskUid']); @@ -169,6 +166,8 @@ public function testGetAllTasksInReverseOrder(): void public function testExceptionIfNoTaskIdWhenGetting(): void { $this->expectException(ApiException::class); + $this->expectExceptionMessage('Task `99999999` not found.'); + $this->index->getTask(99999999); } diff --git a/tests/MockTask.php b/tests/MockTask.php new file mode 100644 index 00000000..c4823978 --- /dev/null +++ b/tests/MockTask.php @@ -0,0 +1,22 @@ +updateDisplayedAttributes($newAttributes); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $displayedAttributes = $index->getDisplayedAttributes(); @@ -45,8 +44,6 @@ public function testResetDisplayedAttributes(): void $promise = $index->resetDisplayedAttributes(); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $displayedAttributes = $index->getDisplayedAttributes(); diff --git a/tests/Settings/DistinctAttributeTest.php b/tests/Settings/DistinctAttributeTest.php index 8afed197..2461d50c 100644 --- a/tests/Settings/DistinctAttributeTest.php +++ b/tests/Settings/DistinctAttributeTest.php @@ -20,15 +20,15 @@ protected function setUp(): void public function testGetDefaultDistinctAttribute(): void { $response = $this->index->getDistinctAttribute(); + self::assertNull($response); } public function testUpdateDistinctAttribute(): void { $distinctAttribute = 'description'; - $promise = $this->index->updateDistinctAttribute($distinctAttribute); - $this->assertIsValidPromise($promise); + $promise = $this->index->updateDistinctAttribute($distinctAttribute); $this->index->waitForTask($promise['taskUid']); self::assertSame($distinctAttribute, $this->index->getDistinctAttribute()); @@ -37,13 +37,13 @@ public function testUpdateDistinctAttribute(): void public function testResetDistinctAttribute(): void { $distinctAttribute = 'description'; + $promise = $this->index->updateDistinctAttribute($distinctAttribute); $this->index->waitForTask($promise['taskUid']); $promise = $this->index->resetDistinctAttribute(); - - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); + self::assertNull($this->index->getDistinctAttribute()); } } diff --git a/tests/Settings/EmbeddersTest.php b/tests/Settings/EmbeddersTest.php index dccb5415..da93d01d 100644 --- a/tests/Settings/EmbeddersTest.php +++ b/tests/Settings/EmbeddersTest.php @@ -32,25 +32,18 @@ public function testUpdateEmbedders(): void $newEmbedders = ['manual' => ['source' => 'userProvided', 'dimensions' => 3, 'binaryQuantized' => true]]; $promise = $this->index->updateEmbedders($newEmbedders); - - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); - $embedders = $this->index->getEmbedders(); - - self::assertSame($newEmbedders, $embedders); + self::assertSame($newEmbedders, $this->index->getEmbedders()); } public function testResetEmbedders(): void { $promise = $this->index->resetEmbedders(); - $this->assertIsValidPromise($promise); - $this->index->waitForTask($promise['taskUid']); - $embedders = $this->index->getEmbedders(); - self::assertSame(self::DEFAULT_EMBEDDER, $embedders); + self::assertSame(self::DEFAULT_EMBEDDER, $this->index->getEmbedders()); } public function testHuggingFacePooling(): void diff --git a/tests/Settings/FacetSearchTest.php b/tests/Settings/FacetSearchTest.php index ae05199b..f4df97b8 100644 --- a/tests/Settings/FacetSearchTest.php +++ b/tests/Settings/FacetSearchTest.php @@ -22,12 +22,9 @@ public function testUpdateFacetSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $promise = $index->updateFacetSearch(false); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); - $facetSearch = $index->getFacetSearch(); - self::assertFalse($facetSearch); + self::assertFalse($index->getFacetSearch()); } public function testResetFacetSearch(): void @@ -38,12 +35,8 @@ public function testResetFacetSearch(): void $index->waitForTask($promise['taskUid']); $promise = $index->resetFacetSearch(); - - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); - $facetSearch = $index->getFacetSearch(); - self::assertTrue($facetSearch); + self::assertTrue($index->getFacetSearch()); } } diff --git a/tests/Settings/FacetingAttributesTest.php b/tests/Settings/FacetingAttributesTest.php index 9c4e0fb2..4bc1f82b 100644 --- a/tests/Settings/FacetingAttributesTest.php +++ b/tests/Settings/FacetingAttributesTest.php @@ -12,14 +12,12 @@ public function testGetDefaultFaceting(): void { $index = $this->createEmptyIndex($this->safeIndexName('books-1')); - $attributes = $index->getFaceting(); - self::assertSame([ 'maxValuesPerFacet' => 100, 'sortFacetValuesBy' => [ '*' => 'alpha', ], - ], $attributes); + ], $index->getFaceting()); } public function testUpdateFacetingAttributes(): void @@ -30,12 +28,10 @@ public function testUpdateFacetingAttributes(): void $promise = $index->updateFaceting($newAttributes); $index->waitForTask($promise['taskUid']); - $faceting = $index->getFaceting(); - self::assertSame([ 'maxValuesPerFacet' => 100, 'sortFacetValuesBy' => ['*' => 'count'], - ], $faceting); + ], $index->getFaceting()); } public function testResetFaceting(): void @@ -49,10 +45,9 @@ public function testResetFaceting(): void $promise = $index->resetFaceting(); $index->waitForTask($promise['taskUid']); - $faceting = $index->getFaceting(); self::assertSame([ 'maxValuesPerFacet' => 100, 'sortFacetValuesBy' => ['*' => 'alpha'], - ], $faceting); + ], $index->getFaceting()); } } diff --git a/tests/Settings/FilterableAttributesTest.php b/tests/Settings/FilterableAttributesTest.php index 6378230b..330324d0 100644 --- a/tests/Settings/FilterableAttributesTest.php +++ b/tests/Settings/FilterableAttributesTest.php @@ -14,7 +14,7 @@ public function testGetDefaultFilterableAttributes(): void $attributes = $index->getFilterableAttributes(); - self::assertEmpty($attributes); + self::assertEmpty($index->getFilterableAttributes()); } public function testUpdateFilterableAttributes(): void @@ -23,13 +23,9 @@ public function testUpdateFilterableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $promise = $index->updateFilterableAttributes($expectedAttributes); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); - $filterableAttributes = $index->getFilterableAttributes(); - - self::assertSame($expectedAttributes, $filterableAttributes); + self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } public function testResetFilterableAttributes(): void @@ -41,13 +37,9 @@ public function testResetFilterableAttributes(): void $index->waitForTask($promise['taskUid']); $promise = $index->resetFilterableAttributes(); - - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); - $filterableAttributes = $index->getFilterableAttributes(); - self::assertEmpty($filterableAttributes); + self::assertEmpty($index->getFilterableAttributes()); } public function testUpdateGranularFilterableAttributes(): void diff --git a/tests/Settings/LocalizedAttributesTest.php b/tests/Settings/LocalizedAttributesTest.php index e905b6a2..68fc5851 100644 --- a/tests/Settings/LocalizedAttributesTest.php +++ b/tests/Settings/LocalizedAttributesTest.php @@ -27,7 +27,6 @@ public function testUpdateLocalizedAttributes(): void $promise = $index->updateLocalizedAttributes($newAttributes); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $localizedAttributes = $index->getLocalizedAttributes(); @@ -44,9 +43,6 @@ public function testResetLocalizedAttributes(): void $index->waitForTask($promise['taskUid']); $promise = $index->resetLocalizedAttributes(); - - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); $localizedAttributes = $index->getLocalizedAttributes(); diff --git a/tests/Settings/NonSeparatorTokensTest.php b/tests/Settings/NonSeparatorTokensTest.php index 5838e2d6..6a4e1ac3 100644 --- a/tests/Settings/NonSeparatorTokensTest.php +++ b/tests/Settings/NonSeparatorTokensTest.php @@ -35,21 +35,16 @@ public function testUpdateNonSeparatorTokens(): void ]; $promise = $this->index->updateNonSeparatorTokens($newNonSeparatorTokens); - $this->index->waitForTask($promise['taskUid']); - $nonSeparatorTokens = $this->index->getNonSeparatorTokens(); - - self::assertSame($newNonSeparatorTokens, $nonSeparatorTokens); + self::assertSame($newNonSeparatorTokens, $this->index->getNonSeparatorTokens()); } public function testResetNonSeparatorTokens(): void { $promise = $this->index->resetNonSeparatorTokens(); - $this->index->waitForTask($promise['taskUid']); - $nonSeparatorTokens = $this->index->getNonSeparatorTokens(); - self::assertSame(self::DEFAULT_NON_SEPARATOR_TOKENS, $nonSeparatorTokens); + self::assertSame(self::DEFAULT_NON_SEPARATOR_TOKENS, $this->index->getNonSeparatorTokens()); } } diff --git a/tests/Settings/PrefixSearchTest.php b/tests/Settings/PrefixSearchTest.php index 2e93bd93..7ceb633d 100644 --- a/tests/Settings/PrefixSearchTest.php +++ b/tests/Settings/PrefixSearchTest.php @@ -22,12 +22,9 @@ public function testUpdatePrefixSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $promise = $index->updatePrefixSearch('disabled'); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); - $prefixSearch = $index->getPrefixSearch(); - self::assertSame('disabled', $prefixSearch); + self::assertSame('disabled', $index->getPrefixSearch()); } public function testResetPrefixSearch(): void @@ -38,12 +35,8 @@ public function testResetPrefixSearch(): void $index->waitForTask($promise['taskUid']); $promise = $index->resetPrefixSearch(); - - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); - $prefixSearch = $index->getPrefixSearch(); - self::assertSame('indexingTime', $prefixSearch); + self::assertSame('indexingTime', $index->getPrefixSearch()); } } diff --git a/tests/Settings/ProximityPrecisionTest.php b/tests/Settings/ProximityPrecisionTest.php index 6372238b..85018008 100644 --- a/tests/Settings/ProximityPrecisionTest.php +++ b/tests/Settings/ProximityPrecisionTest.php @@ -27,7 +27,6 @@ public function testGetDefaultProximityPrecision(): void public function testUpdateProximityPrecision(): void { $promise = $this->index->updateProximityPrecision('byAttribute'); - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); self::assertSame('byAttribute', $this->index->getProximityPrecision()); @@ -36,12 +35,9 @@ public function testUpdateProximityPrecision(): void public function testResetProximityPrecision(): void { $promise = $this->index->updateProximityPrecision('byAttribute'); - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); $promise = $this->index->resetProximityPrecision(); - - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); self::assertSame('byWord', $this->index->getProximityPrecision()); diff --git a/tests/Settings/RankingRulesTest.php b/tests/Settings/RankingRulesTest.php index fc98790f..896f71ce 100644 --- a/tests/Settings/RankingRulesTest.php +++ b/tests/Settings/RankingRulesTest.php @@ -43,7 +43,6 @@ public function testUpdateRankingRules(): void $promise = $this->index->updateRankingRules($newRankingRules); - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); $rankingRules = $this->index->getRankingRules(); @@ -55,8 +54,6 @@ public function testResetRankingRules(): void { $promise = $this->index->resetRankingRules(); - $this->assertIsValidPromise($promise); - $this->index->waitForTask($promise['taskUid']); $rankingRules = $this->index->getRankingRules(); diff --git a/tests/Settings/SearchCutoffMsTest.php b/tests/Settings/SearchCutoffMsTest.php index 656e579d..3d941168 100644 --- a/tests/Settings/SearchCutoffMsTest.php +++ b/tests/Settings/SearchCutoffMsTest.php @@ -27,7 +27,6 @@ public function testGetDefaultSearchCutoffMs(): void public function testUpdateSearchCutoffMs(): void { $promise = $this->index->updateSearchCutoffMs(50); - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); self::assertSame(50, $this->index->getSearchCutoffMs()); @@ -36,12 +35,9 @@ public function testUpdateSearchCutoffMs(): void public function testResetSearchCutoffMs(): void { $promise = $this->index->updateSearchCutoffMs(50); - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); $promise = $this->index->resetSearchCutoffMs(); - - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); self::assertNull($this->index->getSearchCutoffMs()); diff --git a/tests/Settings/SearchableAttributesTest.php b/tests/Settings/SearchableAttributesTest.php index 1515d232..361d67f1 100644 --- a/tests/Settings/SearchableAttributesTest.php +++ b/tests/Settings/SearchableAttributesTest.php @@ -29,25 +29,18 @@ public function testUpdateSearchableAttributes(): void ]; $promise = $indexA->updateSearchableAttributes($searchableAttributes); - - $this->assertIsValidPromise($promise); - $indexA->waitForTask($promise['taskUid']); - $updatedAttributes = $indexA->getSearchableAttributes(); - self::assertSame($searchableAttributes, $updatedAttributes); + self::assertSame($searchableAttributes, $indexA->getSearchableAttributes()); } public function testResetSearchableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName('books-1')); - $promise = $index->resetSearchableAttributes(); - - $this->assertIsValidPromise($promise); + $promise = $index->resetSearchableAttributes(); $index->waitForTask($promise['taskUid']); - $searchableAttributes = $index->getSearchableAttributes(); - self::assertSame(['*'], $searchableAttributes); + self::assertSame(['*'], $index->getSearchableAttributes()); } } diff --git a/tests/Settings/SeparatorTokensTest.php b/tests/Settings/SeparatorTokensTest.php index bbf1de54..185fd890 100644 --- a/tests/Settings/SeparatorTokensTest.php +++ b/tests/Settings/SeparatorTokensTest.php @@ -35,21 +35,16 @@ public function testUpdateSeparatorTokens(): void ]; $promise = $this->index->updateSeparatorTokens($newSeparatorTokens); - $this->index->waitForTask($promise['taskUid']); - $separatorTokens = $this->index->getSeparatorTokens(); - - self::assertSame($newSeparatorTokens, $separatorTokens); + self::assertSame($newSeparatorTokens, $this->index->getSeparatorTokens()); } public function testResetSeparatorTokens(): void { $promise = $this->index->resetSeparatorTokens(); - $this->index->waitForTask($promise['taskUid']); - $separatorTokens = $this->index->getSeparatorTokens(); - self::assertSame(self::DEFAULT_SEPARATOR_TOKENS, $separatorTokens); + self::assertSame(self::DEFAULT_SEPARATOR_TOKENS, $this->index->getSeparatorTokens()); } } diff --git a/tests/Settings/SettingsTest.php b/tests/Settings/SettingsTest.php index 8cbbcac4..ea062690 100644 --- a/tests/Settings/SettingsTest.php +++ b/tests/Settings/SettingsTest.php @@ -84,6 +84,7 @@ public function testGetDefaultSettings(): void public function testUpdateSettings(): void { $index = $this->createEmptyIndex($this->safeIndexName()); + $promise = $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], @@ -91,7 +92,6 @@ public function testUpdateSettings(): void 'facetSearch' => false, 'prefixSearch' => 'disabled', ]); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $settings = $index->getSettings(); @@ -128,21 +128,18 @@ public function testUpdateSettingsWithoutOverwritingThem(): void ]; $index = $this->createEmptyIndex($this->safeIndexName()); + $promise = $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], 'typoTolerance' => $new_typo_tolerance, ]); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $promise = $index->updateSettings([ 'searchableAttributes' => ['title'], ]); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $settings = $index->getSettings(); @@ -165,17 +162,15 @@ public function testUpdateSettingsWithoutOverwritingThem(): void public function testResetSettings(): void { $index = $this->createEmptyIndex($this->safeIndexName()); + $promise = $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], ]); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $promise = $index->resetSettings(); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); $settings = $index->getSettings(); diff --git a/tests/Settings/SortableAttributesTest.php b/tests/Settings/SortableAttributesTest.php index 02698a26..f241dc3f 100644 --- a/tests/Settings/SortableAttributesTest.php +++ b/tests/Settings/SortableAttributesTest.php @@ -12,9 +12,7 @@ public function testGetDefaultSortableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $attributes = $index->getSortableAttributes(); - - self::assertEmpty($attributes); + self::assertEmpty($index->getSortableAttributes()); } public function testUpdateSortableAttributes(): void @@ -23,13 +21,9 @@ public function testUpdateSortableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $promise = $index->updateSortableAttributes($newAttributes); - - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); - $sortableAttributes = $index->getSortableAttributes(); - - self::assertSame($newAttributes, $sortableAttributes); + self::assertSame($newAttributes, $index->getSortableAttributes()); } public function testResetSortableAttributes(): void @@ -41,12 +35,8 @@ public function testResetSortableAttributes(): void $index->waitForTask($promise['taskUid']); $promise = $index->resetSortableAttributes(); - - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); - $sortableAttributes = $index->getSortableAttributes(); - self::assertEmpty($sortableAttributes); + self::assertEmpty($index->getSortableAttributes()); } } diff --git a/tests/Settings/StopWordsTest.php b/tests/Settings/StopWordsTest.php index 4a7148a6..cb823cc7 100644 --- a/tests/Settings/StopWordsTest.php +++ b/tests/Settings/StopWordsTest.php @@ -29,12 +29,9 @@ public function testUpdateStopWords(): void $newStopWords = ['the']; $promise = $this->index->updateStopWords($newStopWords); - $this->assertIsValidPromise($promise); - $this->index->waitForTask($promise['taskUid']); - $stopWords = $this->index->getStopWords(); - self::assertSame($newStopWords, $stopWords); + self::assertSame($newStopWords, $this->index->getStopWords()); } public function testResetStopWords(): void @@ -43,12 +40,8 @@ public function testResetStopWords(): void $this->index->waitForTask($promise['taskUid']); $promise = $this->index->resetStopWords(); - - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); - $stopWords = $this->index->getStopWords(); - - self::assertEmpty($stopWords); + self::assertEmpty($this->index->getStopWords()); } } diff --git a/tests/Settings/SynonymsTest.php b/tests/Settings/SynonymsTest.php index 121dbda5..7fb02361 100644 --- a/tests/Settings/SynonymsTest.php +++ b/tests/Settings/SynonymsTest.php @@ -27,27 +27,21 @@ public function testUpdateSynonyms(): void $newSynonyms = [ 'hp' => ['harry potter'], ]; - $promise = $this->index->updateSynonyms($newSynonyms); - - $this->assertIsValidPromise($promise); + $promise = $this->index->updateSynonyms($newSynonyms); $this->index->waitForTask($promise['taskUid']); - $synonyms = $this->index->getSynonyms(); - self::assertSame($newSynonyms, $synonyms); + self::assertSame($newSynonyms, $this->index->getSynonyms()); } public function testUpdateSynonymsWithEmptyArray(): void { $newSynonyms = []; - $promise = $this->index->updateSynonyms($newSynonyms); - - $this->assertIsValidPromise($promise); + $promise = $this->index->updateSynonyms($newSynonyms); $this->index->waitForTask($promise['taskUid']); - $synonyms = $this->index->getSynonyms(); - self::assertSame($newSynonyms, $synonyms); + self::assertSame($newSynonyms, $this->index->getSynonyms()); } public function testResetSynonyms(): void @@ -58,11 +52,8 @@ public function testResetSynonyms(): void $this->index->waitForTask($promise['taskUid']); $promise = $this->index->resetSynonyms(); - $this->assertIsValidPromise($promise); - $this->index->waitForTask($promise['taskUid']); - $synonyms = $this->index->getSynonyms(); - self::assertEmpty($synonyms); + self::assertEmpty($this->index->getSynonyms()); } } diff --git a/tests/Settings/TypoToleranceTest.php b/tests/Settings/TypoToleranceTest.php index 4c8f3fad..1f767392 100644 --- a/tests/Settings/TypoToleranceTest.php +++ b/tests/Settings/TypoToleranceTest.php @@ -51,7 +51,6 @@ public function testUpdateTypoTolerance(): void $this->index->waitForTask($promise['taskUid']); $typoTolerance = $this->index->getTypoTolerance(); - $this->assertIsValidPromise($promise); self::assertSame($newTypoTolerance, $typoTolerance); } @@ -61,7 +60,6 @@ public function testResetTypoTolerance(): void $this->index->waitForTask($promise['taskUid']); $typoTolerance = $this->index->getTypoTolerance(); - $this->assertIsValidPromise($promise); self::assertSame(self::DEFAULT_TYPO_TOLERANCE, $typoTolerance); } } diff --git a/tests/Settings/WordDictionaryTest.php b/tests/Settings/WordDictionaryTest.php index f8a4fbdc..bb98a691 100644 --- a/tests/Settings/WordDictionaryTest.php +++ b/tests/Settings/WordDictionaryTest.php @@ -21,9 +21,7 @@ protected function setUp(): void public function testGetDefaultWordDictionary(): void { - $response = $this->index->getDictionary(); - - self::assertSame(self::DEFAULT_WORD_DICTIONARY, $response); + self::assertSame(self::DEFAULT_WORD_DICTIONARY, $this->index->getDictionary()); } public function testUpdateWordDictionary(): void @@ -34,21 +32,16 @@ public function testUpdateWordDictionary(): void ]; $promise = $this->index->updateDictionary($newWordDictionary); - $this->index->waitForTask($promise['taskUid']); - $wordDictionary = $this->index->getDictionary(); - - self::assertSame($newWordDictionary, $wordDictionary); + self::assertSame($newWordDictionary, $this->index->getDictionary()); } public function testResetWordDictionary(): void { $promise = $this->index->resetDictionary(); - $this->index->waitForTask($promise['taskUid']); - $wordDictionary = $this->index->getDictionary(); - self::assertSame(self::DEFAULT_WORD_DICTIONARY, $wordDictionary); + self::assertSame(self::DEFAULT_WORD_DICTIONARY, $this->index->getDictionary()); } } From a4091a98d338566bb630c4c95639c22c9ae9d6cd Mon Sep 17 00:00:00 2001 From: Tomas Date: Thu, 10 Apr 2025 06:56:39 +0300 Subject: [PATCH 05/51] Add tests for missing coverage report --- tests/Contracts/TaskTest.php | 21 +++++++++++++ tests/Settings/PaginationTest.php | 51 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 tests/Settings/PaginationTest.php diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index 6e29fdac..9cc1f5cd 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -8,6 +8,7 @@ use MeiliSearch\Contracts\TaskStatus; use MeiliSearch\Contracts\TaskType; use PHPUnit\Framework\TestCase; +use Tests\MockTask; final class TaskTest extends TestCase { @@ -88,4 +89,24 @@ public function testCreateEnqueuedTask(): void self::assertNull($task->getDetails()); self::assertNull($task->getError()); } + + public function testArraySetThrows(): void + { + $task = MockTask::create(TaskType::IndexCreation); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('Setting data on "MeiliSearch\Contracts\Task::type" is not supported.'); + + $task['type'] = TaskType::IndexDeletion; + } + + public function testArrayUnsetThrows(): void + { + $task = MockTask::create(TaskType::IndexCreation); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('Unsetting data on "MeiliSearch\Contracts\Task::type" is not supported.'); + + unset($task['type']); + } } diff --git a/tests/Settings/PaginationTest.php b/tests/Settings/PaginationTest.php new file mode 100644 index 00000000..8cb0b9e9 --- /dev/null +++ b/tests/Settings/PaginationTest.php @@ -0,0 +1,51 @@ + 1000, + ]; + + protected function setUp(): void + { + parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); + } + + public function testGetDefaultPagination(): void + { + $response = $this->index->getPagination(); + + self::assertSame(self::DEFAULT_PAGINATION, $response); + } + + public function testUpdatePagination(): void + { + $promise = $this->index->updatePagination(['maxTotalHits' => 100]); + + $this->index->waitForTask($promise['taskUid']); + + self::assertSame(['maxTotalHits' => 100], $this->index->getPagination()); + } + + public function testResetRankingRules(): void + { + $promise = $this->index->updatePagination(['maxTotalHits' => 100]); + + $this->index->waitForTask($promise['taskUid']); + + $promise = $this->index->resetPagination(); + $this->index->waitForTask($promise['taskUid']); + + self::assertSame(self::DEFAULT_PAGINATION, $this->index->getPagination()); + } +} From 204f354eaab062fb2b2b29c8a9d94bd4421812c3 Mon Sep 17 00:00:00 2001 From: Tomas Date: Mon, 5 May 2025 09:31:56 +0300 Subject: [PATCH 06/51] Fix conflicts --- tests/Settings/EmbeddersTest.php | 4 ++-- tests/Settings/FilterableAttributesTest.php | 11 ++++------- tests/TestCase.php | 5 ----- 3 files changed, 6 insertions(+), 14 deletions(-) diff --git a/tests/Settings/EmbeddersTest.php b/tests/Settings/EmbeddersTest.php index da93d01d..8bfd7eab 100644 --- a/tests/Settings/EmbeddersTest.php +++ b/tests/Settings/EmbeddersTest.php @@ -4,6 +4,7 @@ namespace Tests\Settings; +use MeiliSearch\Contracts\TaskStatus; use Meilisearch\Endpoints\Indexes; use Meilisearch\Http\Client; use Tests\TestCase; @@ -62,7 +63,6 @@ public function testHuggingFacePooling(): void ], ]); - $this->assertIsValidPromise($promise); $this->index->waitForTask($promise['taskUid']); $embedders = $this->index->getEmbedders(); @@ -93,6 +93,6 @@ public function testCompositeEmbedder(): void 'embedder_name' => $embedder, ]); - $this->assertIsValidPromise($promise); + self::assertSame(TaskStatus::Enqueued, $promise->getStatus()); } } diff --git a/tests/Settings/FilterableAttributesTest.php b/tests/Settings/FilterableAttributesTest.php index 330324d0..24bfddb1 100644 --- a/tests/Settings/FilterableAttributesTest.php +++ b/tests/Settings/FilterableAttributesTest.php @@ -61,11 +61,9 @@ public function testUpdateGranularFilterableAttributes(): void ]; $promise = $index->updateFilterableAttributes($expectedAttributes); - $this->assertIsValidPromise($promise); - $index->waitForTask($promise['taskUid']); - $filterableAttributes = $index->getFilterableAttributes(); - self::assertSame($expectedAttributes, $filterableAttributes); + + self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } public function testUpdateGeoWithGranularFilterableAttributes(): void @@ -77,10 +75,9 @@ public function testUpdateGeoWithGranularFilterableAttributes(): void 'attributePatterns' => ['_geo'], ], ]); - $this->assertIsValidPromise($promise); $index->waitForTask($promise['taskUid']); - $filterableAttributes = $index->getFilterableAttributes(); + self::assertSame([ [ 'attributePatterns' => ['_geo'], @@ -92,6 +89,6 @@ public function testUpdateGeoWithGranularFilterableAttributes(): void ], ], ], - ], $filterableAttributes); + ], $index->getFilterableAttributes()); } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 40659830..49ace79a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -97,11 +97,6 @@ protected function tearDown(): void $this->client->waitForTasks($tasks); } - public function assertIsValidPromise(array $promise): void - { - self::assertArrayHasKey('taskUid', $promise); - } - public function assertFinitePagination(array $response): void { $currentKeys = array_keys($response); From 444e39166455b1cfeccef253e689ddbb1a736766 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:25:31 +0300 Subject: [PATCH 07/51] Remove unused variable --- tests/Settings/FilterableAttributesTest.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/Settings/FilterableAttributesTest.php b/tests/Settings/FilterableAttributesTest.php index 24bfddb1..ba88a8c6 100644 --- a/tests/Settings/FilterableAttributesTest.php +++ b/tests/Settings/FilterableAttributesTest.php @@ -12,8 +12,6 @@ public function testGetDefaultFilterableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $attributes = $index->getFilterableAttributes(); - self::assertEmpty($index->getFilterableAttributes()); } From b7d0c9c3a3fc98a7c0478fc4daea004a76a07423 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:33:45 +0300 Subject: [PATCH 08/51] Fix test method name --- tests/Settings/PaginationTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Settings/PaginationTest.php b/tests/Settings/PaginationTest.php index 8cb0b9e9..7193af85 100644 --- a/tests/Settings/PaginationTest.php +++ b/tests/Settings/PaginationTest.php @@ -37,7 +37,7 @@ public function testUpdatePagination(): void self::assertSame(['maxTotalHits' => 100], $this->index->getPagination()); } - public function testResetRankingRules(): void + public function testResetPagination(): void { $promise = $this->index->updatePagination(['maxTotalHits' => 100]); From 12e4e1a3044870cb9a29199e8a3483e94105449e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:37:11 +0300 Subject: [PATCH 09/51] Add a missing phpdoc type for documentId validation --- src/Endpoints/Delegates/HandlesDocuments.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Endpoints/Delegates/HandlesDocuments.php b/src/Endpoints/Delegates/HandlesDocuments.php index b40a5cff..eb2a08d2 100644 --- a/src/Endpoints/Delegates/HandlesDocuments.php +++ b/src/Endpoints/Delegates/HandlesDocuments.php @@ -12,6 +12,9 @@ trait HandlesDocuments { + /** + * @param non-empty-string|int $documentId + */ public function getDocument(string|int $documentId, ?array $fields = null): array { $query = isset($fields) ? ['fields' => implode(',', $fields)] : []; From fe3c1ff86ddebe849c696289cf0bb278a8f5ff4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:38:28 +0300 Subject: [PATCH 10/51] Remove task type that does not exist --- src/Contracts/TaskType.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Contracts/TaskType.php b/src/Contracts/TaskType.php index 2eabfe29..64f1207b 100644 --- a/src/Contracts/TaskType.php +++ b/src/Contracts/TaskType.php @@ -12,7 +12,6 @@ enum TaskType: string case IndexSwap = 'indexSwap'; case DocumentAdditionOrUpdate = 'documentAdditionOrUpdate'; case DocumentDeletion = 'documentDeletion'; - case DocumentEdition = 'documentEdition'; case SettingsUpdate = 'settingsUpdate'; case DumpCreation = 'dumpCreation'; case TaskCancelation = 'taskCancelation'; From 6cb7c0e53dd13ad0304cfbc8eeefcaaefffd6b12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:40:16 +0300 Subject: [PATCH 11/51] Add comment about array access retrocompatibility --- tests/Contracts/TaskTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index 9cc1f5cd..78f13714 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -59,6 +59,7 @@ public function testCreate(): void 'link' => 'https://docs.meilisearch.com/errors#index_not_found', ], $task->getError()); + // Ensure the class supports array access retrocompatibility self::assertSame(1, $task['taskUid']); self::assertSame('documents', $task['indexUid']); self::assertSame('failed', $task['status']); From 23813aca06bc2d6602cae9d339688bb133003d17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:41:46 +0300 Subject: [PATCH 12/51] Fix tests after `TaskType::documentEdition` removal --- tests/Endpoints/DocumentsTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 1d9e4fac..08f2382a 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -373,11 +373,11 @@ public function testAddDocumentsCsvInBatchesWithDelimiter(): void case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentEdition); + return MockTask::create(TaskType::DocumentAdditionOrUpdate); case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentEdition); + return MockTask::create(TaskType::DocumentAdditionOrUpdate); default: self::fail(); } @@ -874,11 +874,11 @@ public function testUpdateDocumentsCsvInBatchesWithDelimiter(): void case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentEdition); + return MockTask::create(TaskType::DocumentAdditionOrUpdate); case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentEdition); + return MockTask::create(TaskType::DocumentAdditionOrUpdate); default: self::fail(); } From 412c8bd9cee6f42f4b8de59a0cc07e3a2a405dc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:44:57 +0300 Subject: [PATCH 13/51] Revert "Fix tests after `TaskType::documentEdition` removal" This reverts commit e17e0bb81b2aa19f0f9f04f1487bbaddbf927c0a. --- tests/Endpoints/DocumentsTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 08f2382a..1d9e4fac 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -373,11 +373,11 @@ public function testAddDocumentsCsvInBatchesWithDelimiter(): void case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentAdditionOrUpdate); + return MockTask::create(TaskType::DocumentEdition); case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentAdditionOrUpdate); + return MockTask::create(TaskType::DocumentEdition); default: self::fail(); } @@ -874,11 +874,11 @@ public function testUpdateDocumentsCsvInBatchesWithDelimiter(): void case 1: self::assertSame(["id;title\n888221515;Young folks", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentAdditionOrUpdate); + return MockTask::create(TaskType::DocumentEdition); case 2: self::assertSame(["id;title\n235115704;Mister Klein", null, ';'], [$documents, $primaryKey, $delimiter]); - return MockTask::create(TaskType::DocumentAdditionOrUpdate); + return MockTask::create(TaskType::DocumentEdition); default: self::fail(); } From c5236844ba3544de485982078ad8689d4ec86bf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:45:08 +0300 Subject: [PATCH 14/51] Revert "Remove task type that does not exist" This reverts commit 9d29e14272e284d2f0ad265ac9b58de01b04fd27. --- src/Contracts/TaskType.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Contracts/TaskType.php b/src/Contracts/TaskType.php index 64f1207b..2eabfe29 100644 --- a/src/Contracts/TaskType.php +++ b/src/Contracts/TaskType.php @@ -12,6 +12,7 @@ enum TaskType: string case IndexSwap = 'indexSwap'; case DocumentAdditionOrUpdate = 'documentAdditionOrUpdate'; case DocumentDeletion = 'documentDeletion'; + case DocumentEdition = 'documentEdition'; case SettingsUpdate = 'settingsUpdate'; case DumpCreation = 'dumpCreation'; case TaskCancelation = 'taskCancelation'; From 6a601dafb5ff0f4f687ec6613db95e2d715658ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 07:54:20 +0300 Subject: [PATCH 15/51] Add a `non-negative-int` hint for `searchCutoffMs` setting value --- src/Endpoints/Delegates/HandlesSettings.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Endpoints/Delegates/HandlesSettings.php b/src/Endpoints/Delegates/HandlesSettings.php index 7cfa82f6..62a9a198 100644 --- a/src/Endpoints/Delegates/HandlesSettings.php +++ b/src/Endpoints/Delegates/HandlesSettings.php @@ -404,11 +404,17 @@ public function resetProximityPrecision(): Task // Settings - searchCutoffMs + /** + * @return non-negative-int|null + */ public function getSearchCutoffMs(): ?int { return $this->http->get(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms'); } + /** + * @param non-negative-int $value + */ public function updateSearchCutoffMs(int $value): Task { return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms', $value)); From 757f5cff0c3327dc3b15bc6936e1af544195a611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 12:46:10 +0300 Subject: [PATCH 16/51] Add typed TaskDetails and TaskError + fix namespace casing --- src/Contracts/Task.php | 61 +++++--- src/Contracts/TaskDetails.php | 16 ++ .../DocumentAdditionOrUpdateDetails.php | 34 ++++ .../TaskDetails/DocumentDeletionDetails.php | 38 +++++ .../TaskDetails/DocumentEditionDetails.php | 42 +++++ .../TaskDetails/DumpCreationDetails.php | 30 ++++ .../TaskDetails/IndexCreationDetails.php | 30 ++++ .../TaskDetails/IndexDeletionDetails.php | 30 ++++ .../TaskDetails/IndexSwapDetails.php | 30 ++++ .../TaskDetails/IndexUpdateDetails.php | 30 ++++ .../TaskDetails/SettingsUpdateDetails.php | 146 ++++++++++++++++++ .../TaskDetails/TaskCancelationDetails.php | 38 +++++ .../TaskDetails/TaskDeletionDetails.php | 38 +++++ src/Contracts/TaskError.php | 40 +++++ src/Contracts/TaskStatus.php | 2 +- src/Contracts/TaskType.php | 2 +- src/Endpoints/Delegates/HandlesDocuments.php | 2 +- src/Endpoints/Delegates/HandlesDumps.php | 2 +- src/Endpoints/Delegates/HandlesIndex.php | 2 +- src/Endpoints/Delegates/HandlesSettings.php | 2 +- src/Endpoints/Delegates/HandlesSnapshots.php | 2 +- src/Endpoints/Delegates/HandlesSystem.php | 2 +- src/Endpoints/Delegates/HandlesTasks.php | 2 +- src/Endpoints/Dumps.php | 2 +- src/Endpoints/Indexes.php | 2 +- src/Endpoints/Snapshots.php | 2 +- src/Endpoints/Tasks.php | 2 +- tests/Contracts/TaskTest.php | 40 ++--- tests/Endpoints/DocumentsTest.php | 4 +- tests/Endpoints/DumpTest.php | 2 +- tests/Endpoints/SnapshotsTest.php | 2 +- tests/MockTask.php | 6 +- tests/Settings/EmbeddersTest.php | 2 +- 33 files changed, 620 insertions(+), 65 deletions(-) create mode 100644 src/Contracts/TaskDetails.php create mode 100644 src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php create mode 100644 src/Contracts/TaskDetails/DocumentDeletionDetails.php create mode 100644 src/Contracts/TaskDetails/DocumentEditionDetails.php create mode 100644 src/Contracts/TaskDetails/DumpCreationDetails.php create mode 100644 src/Contracts/TaskDetails/IndexCreationDetails.php create mode 100644 src/Contracts/TaskDetails/IndexDeletionDetails.php create mode 100644 src/Contracts/TaskDetails/IndexSwapDetails.php create mode 100644 src/Contracts/TaskDetails/IndexUpdateDetails.php create mode 100644 src/Contracts/TaskDetails/SettingsUpdateDetails.php create mode 100644 src/Contracts/TaskDetails/TaskCancelationDetails.php create mode 100644 src/Contracts/TaskDetails/TaskDeletionDetails.php create mode 100644 src/Contracts/TaskError.php diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index cf262c54..d674dedd 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -2,20 +2,26 @@ declare(strict_types=1); -namespace MeiliSearch\Contracts; +namespace Meilisearch\Contracts; + +use Meilisearch\Contracts\TaskDetails\DocumentAdditionOrUpdateDetails; +use Meilisearch\Contracts\TaskDetails\DocumentDeletionDetails; +use Meilisearch\Contracts\TaskDetails\DocumentEditionDetails; +use Meilisearch\Contracts\TaskDetails\DumpCreationDetails; +use Meilisearch\Contracts\TaskDetails\IndexCreationDetails; +use Meilisearch\Contracts\TaskDetails\IndexDeletionDetails; +use Meilisearch\Contracts\TaskDetails\IndexSwapDetails; +use Meilisearch\Contracts\TaskDetails\IndexUpdateDetails; +use Meilisearch\Contracts\TaskDetails\SettingsUpdateDetails; +use Meilisearch\Contracts\TaskDetails\TaskCancelationDetails; +use Meilisearch\Contracts\TaskDetails\TaskDeletionDetails; final class Task implements \ArrayAccess { /** * @param non-negative-int $taskUid * @param non-empty-string|null $indexUid - * @param array{ - * message: non-empty-string, - * code: non-empty-string, - * type: non-empty-string, - * link: non-empty-string - * }|null $error - * @param array $data Raw data + * @param array $data Raw data */ public function __construct( private readonly int $taskUid, @@ -28,8 +34,8 @@ public function __construct( private readonly ?string $duration = null, private readonly ?int $canceledBy = null, private readonly ?int $batchUid = null, - private readonly ?array $details = null, - private readonly ?array $error = null, + private readonly ?TaskDetails $details = null, + private readonly ?TaskError $error = null, private readonly array $data = [], ) { } @@ -90,20 +96,12 @@ public function getBatchUid(): ?int return $this->batchUid; } - public function getDetails(): ?array + public function getDetails(): ?TaskDetails { return $this->details; } - /** - * @return array{ - * message: non-empty-string, - * code: non-empty-string, - * type: non-empty-string, - * link: non-empty-string - * }|null - */ - public function getError(): ?array + public function getError(): ?TaskError { return $this->error; } @@ -158,8 +156,8 @@ public function isFinished(): bool * duration?: non-empty-string, * canceledBy?: int, * batchUid?: int, - * details?: array, - * error?: array, + * details?: array|null, + * error?: array|null, * data: array * } $data */ @@ -169,15 +167,28 @@ public static function fromArray(array $data): Task $data['taskUid'] ?? $data['uid'], $data['indexUid'], TaskStatus::from($data['status']), - TaskType::from($data['type']), + $type = TaskType::from($data['type']), new \DateTimeImmutable($data['enqueuedAt']), isset($data['startedAt']) ? new \DateTimeImmutable($data['startedAt']) : null, isset($data['finishedAt']) ? new \DateTimeImmutable($data['finishedAt']) : null, $data['duration'] ?? null, $data['canceledBy'] ?? null, $data['batchUid'] ?? null, - $data['details'] ?? null, - $data['error'] ?? null, + match ($type) { + TaskType::IndexCreation => null !== $data['details'] ? IndexCreationDetails::fromArray($data['details']) : null, + TaskType::IndexUpdate => null !== $data['details'] ? IndexUpdateDetails::fromArray($data['details']) : null, + TaskType::IndexDeletion => null !== $data['details'] ? IndexDeletionDetails::fromArray($data['details']) : null, + TaskType::IndexSwap => null !== $data['details'] ? IndexSwapDetails::fromArray($data['details']) : null, + TaskType::DocumentAdditionOrUpdate => null !== $data['details'] ? DocumentAdditionOrUpdateDetails::fromArray($data['details']) : null, + TaskType::DocumentDeletion => null !== $data['details'] ? DocumentDeletionDetails::fromArray($data['details']) : null, + TaskType::DocumentEdition => null !== $data['details'] ? DocumentEditionDetails::fromArray($data['details']) : null, + TaskType::SettingsUpdate => null !== $data['details'] ? SettingsUpdateDetails::fromArray($data['details']) : null, + TaskType::DumpCreation => null !== $data['details'] ? DumpCreationDetails::fromArray($data['details']) : null, + TaskType::TaskCancelation => null !== $data['details'] ? TaskCancelationDetails::fromArray($data['details']) : null, + TaskType::TaskDeletion => null !== $data['details'] ? TaskDeletionDetails::fromArray($data['details']) : null, + TaskType::SnapshotCreation => null, + }, + null !== $data['error'] ? TaskError::fromArray($data['error']) : null, $data, ); } diff --git a/src/Contracts/TaskDetails.php b/src/Contracts/TaskDetails.php new file mode 100644 index 00000000..44cffa08 --- /dev/null +++ b/src/Contracts/TaskDetails.php @@ -0,0 +1,16 @@ + + */ +final class DocumentAdditionOrUpdateDetails implements TaskDetails +{ + /** + * @param non-negative-int $receivedDocuments Number of documents received + * @param non-negative-int|null $indexedDocuments Number of documents indexed. `null` while the task status is enqueued or processing. + */ + public function __construct( + public readonly int $receivedDocuments, + public readonly ?int $indexedDocuments, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['receivedDocuments'], + $data['indexedDocuments'] ?? null, + ); + } +} diff --git a/src/Contracts/TaskDetails/DocumentDeletionDetails.php b/src/Contracts/TaskDetails/DocumentDeletionDetails.php new file mode 100644 index 00000000..11dd782c --- /dev/null +++ b/src/Contracts/TaskDetails/DocumentDeletionDetails.php @@ -0,0 +1,38 @@ + + */ +final class DocumentDeletionDetails implements TaskDetails +{ + /** + * @param non-negative-int|null $providedIds Number of documents queued for deletion + * @param string|null $originalFilter The filter used to delete documents. Null if it was not specified. + * @param int|null $deletedDocuments Number of documents deleted. `null` while the task status is enqueued or processing. + */ + public function __construct( + public readonly ?int $providedIds, + public readonly ?string $originalFilter, + public readonly ?int $deletedDocuments, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['providedIds'], + $data['originalFilter'] ?? null, + $data['deletedDocuments'] ?? null, + ); + } +} diff --git a/src/Contracts/TaskDetails/DocumentEditionDetails.php b/src/Contracts/TaskDetails/DocumentEditionDetails.php new file mode 100644 index 00000000..1f11b314 --- /dev/null +++ b/src/Contracts/TaskDetails/DocumentEditionDetails.php @@ -0,0 +1,42 @@ +, + * deletedDocuments: non-negative-int|null, + * editedDocuments: non-negative-int|null, + * function: string|null, + * originalFilter: string|null + * }> + */ +final class DocumentEditionDetails implements TaskDetails +{ + /** + * @param array $context + */ + public function __construct( + public readonly array $context, + public readonly ?int $deletedDocuments, + public readonly ?int $editedDocuments, + public readonly ?string $function, + public readonly ?string $originalFilter, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['context'], + $data['deletedDocuments'], + $data['deletedDocuments'], + $data['function'], + $data['originalFilter'], + ); + } +} diff --git a/src/Contracts/TaskDetails/DumpCreationDetails.php b/src/Contracts/TaskDetails/DumpCreationDetails.php new file mode 100644 index 00000000..14f34edb --- /dev/null +++ b/src/Contracts/TaskDetails/DumpCreationDetails.php @@ -0,0 +1,30 @@ + + */ +final class DumpCreationDetails implements TaskDetails +{ + /** + * @param non-empty-string|null $dumpUid + */ + public function __construct( + public readonly ?string $dumpUid, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['dumpUid'], + ); + } +} diff --git a/src/Contracts/TaskDetails/IndexCreationDetails.php b/src/Contracts/TaskDetails/IndexCreationDetails.php new file mode 100644 index 00000000..98e576ad --- /dev/null +++ b/src/Contracts/TaskDetails/IndexCreationDetails.php @@ -0,0 +1,30 @@ + + */ +final class IndexCreationDetails implements TaskDetails +{ + /** + * @param non-empty-string|null $primaryKey Value of the primaryKey field supplied during index creation. `null` if it was not specified. + */ + public function __construct( + public readonly ?string $primaryKey, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['primaryKey'], + ); + } +} diff --git a/src/Contracts/TaskDetails/IndexDeletionDetails.php b/src/Contracts/TaskDetails/IndexDeletionDetails.php new file mode 100644 index 00000000..095cd7d5 --- /dev/null +++ b/src/Contracts/TaskDetails/IndexDeletionDetails.php @@ -0,0 +1,30 @@ + + */ +final class IndexDeletionDetails implements TaskDetails +{ + /** + * @param non-negative-int|null $deletedDocuments Number of deleted documents. This should equal the total number of documents in the deleted index. `null` while the task status is enqueued or processing. + */ + public function __construct( + public readonly ?int $deletedDocuments, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['deletedDocuments'], + ); + } +} diff --git a/src/Contracts/TaskDetails/IndexSwapDetails.php b/src/Contracts/TaskDetails/IndexSwapDetails.php new file mode 100644 index 00000000..56493685 --- /dev/null +++ b/src/Contracts/TaskDetails/IndexSwapDetails.php @@ -0,0 +1,30 @@ + + * }> + */ +final class IndexSwapDetails implements TaskDetails +{ + /** + * @param array $swaps + */ + public function __construct( + public readonly array $swaps, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['swaps'], + ); + } +} diff --git a/src/Contracts/TaskDetails/IndexUpdateDetails.php b/src/Contracts/TaskDetails/IndexUpdateDetails.php new file mode 100644 index 00000000..7603a081 --- /dev/null +++ b/src/Contracts/TaskDetails/IndexUpdateDetails.php @@ -0,0 +1,30 @@ + + */ +final class IndexUpdateDetails implements TaskDetails +{ + /** + * @param non-empty-string|null $primaryKey Value of the primaryKey field supplied during index creation. `null` if it was not specified. + */ + public function __construct( + public readonly ?string $primaryKey, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['primaryKey'], + ); + } +} diff --git a/src/Contracts/TaskDetails/SettingsUpdateDetails.php b/src/Contracts/TaskDetails/SettingsUpdateDetails.php new file mode 100644 index 00000000..af848dd0 --- /dev/null +++ b/src/Contracts/TaskDetails/SettingsUpdateDetails.php @@ -0,0 +1,146 @@ +, + * displayedAttributes?: list, + * distinctAttribute?: string, + * embedders?: non-empty-array, + * response?: array, + * revision?: string, + * searchEmbedder?: array{model: string, source: string}, + * source?: string, + * url?: string + * }>, + * faceting?: array{maxValuesPerFacet: non-negative-int, sortFacetValuesBy: array}|null, + * facetSearch?: bool, + * filterableAttributes?: list, features: array{facetSearch: bool, filter: array{equality: bool, comparison: bool}}}>|null, + * localizedAttributes?: list, attributePatterns: list}>, + * nonSeparatorTokens?: list, + * pagination?: array{maxTotalHits: non-negative-int}, + * prefixSearch?: non-empty-string|null, + * proximityPrecision?: 'byWord'|'byAttribute', + * rankingRules?: list, + * searchableAttributes?: list, + * searchCutoffMs?: non-negative-int, + * separatorTokens?: list, + * sortableAttributes?: list, + * stopWords?: list, + * synonyms?: array>, + * typoTolerance?: array{ + * enabled: bool, + * minWordSizeForTypos: array{oneTypo: int, twoTypos: int}, + * disableOnWords: list, + * disableOnAttributes: list + * } + * }> + */ +final class SettingsUpdateDetails implements TaskDetails +{ + /** + * @param list|null $dictionary + * @param list|null $displayedAttributes + * @param non-empty-array, + * response?: array, + * revision?: string, + * searchEmbedder?: array{model: string, source: string}, + * source?: string, + * url?: string + * }>|null $embedders + * @param array{maxValuesPerFacet: non-negative-int, sortFacetValuesBy: array}|null $faceting + * @param list, features: array{facetSearch: bool, filter: array{equality: bool, comparison: bool}}}>|null $filterableAttributes + * @param list, attributePatterns: list}>|null $localizedAttributes + * @param list|null $nonSeparatorTokens + * @param array{maxTotalHits: non-negative-int}|null $pagination + * @param 'indexingTime'|'disabled'|null $prefixSearch + * @param 'byWord'|'byAttribute'|null $proximityPrecision + * @param list|null $rankingRules + * @param list|null $searchableAttributes + * @param non-negative-int|null $searchCutoffMs + * @param list $separatorTokens + * @param list|null $sortableAttributes + * @param list|null $stopWords + * @param array>|null $synonyms + * @param array{ + * enabled: bool, + * minWordSizeForTypos: array{oneTypo: int, twoTypos: int}, + * disableOnWords: list, + * disableOnAttributes: list + * }|null $typoTolerance + */ + public function __construct( + public readonly ?array $dictionary, + public readonly ?array $displayedAttributes, + public readonly ?string $distinctAttribute, + public readonly ?array $embedders, + public readonly ?array $faceting, + public readonly ?bool $facetSearch, + public readonly ?array $filterableAttributes, + public readonly ?array $localizedAttributes, + public readonly ?array $nonSeparatorTokens, + public readonly ?array $pagination, + public readonly ?string $prefixSearch, + public readonly ?string $proximityPrecision, + public readonly ?array $rankingRules, + public readonly ?array $searchableAttributes, + public readonly ?int $searchCutoffMs, + public readonly ?array $separatorTokens, + public readonly ?array $sortableAttributes, + public readonly ?array $stopWords, + public readonly ?array $synonyms, + public readonly ?array $typoTolerance, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['dictionary'] ?? null, + $data['displayedAttributes'] ?? null, + $data['distinctAttribute'] ?? null, + $data['embedders'] ?? null, + $data['faceting'] ?? null, + $data['facetSearch'] ?? null, + $data['filterableAttributes'] ?? null, + $data['localizedAttributes'] ?? null, + $data['nonSeparatorTokens'] ?? null, + $data['pagination'] ?? null, + $data['prefixSearch'] ?? null, + $data['proximityPrecision'] ?? null, + $data['rankingRules'] ?? null, + $data['searchableAttributes'] ?? null, + $data['searchCutoffMs'] ?? null, + $data['separatorTokens'] ?? null, + $data['sortableAttributes'] ?? null, + $data['stopWords'] ?? null, + $data['synonyms'] ?? null, + $data['typoTolerance'] ?? null, + ); + } +} diff --git a/src/Contracts/TaskDetails/TaskCancelationDetails.php b/src/Contracts/TaskDetails/TaskCancelationDetails.php new file mode 100644 index 00000000..2d394cb7 --- /dev/null +++ b/src/Contracts/TaskDetails/TaskCancelationDetails.php @@ -0,0 +1,38 @@ + + */ +final class TaskCancelationDetails implements TaskDetails +{ + /** + * @param non-negative-int|null $matchedTasks The number of matched tasks. If the API key used for the request doesn’t have access to an index, tasks relating to that index will not be included in matchedTasks. + * @param non-negative-int|null $canceledTasks The number of tasks successfully canceled. If the task cancellation fails, this will be 0. null when the task status is enqueued or processing. + * @param string|null $originalFilter the filter used in the cancel task request + */ + public function __construct( + public readonly ?int $matchedTasks, + public readonly ?int $canceledTasks, + public readonly ?string $originalFilter, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['matchedTasks'], + $data['canceledTasks'], + $data['originalFilter'], + ); + } +} diff --git a/src/Contracts/TaskDetails/TaskDeletionDetails.php b/src/Contracts/TaskDetails/TaskDeletionDetails.php new file mode 100644 index 00000000..7fabb30d --- /dev/null +++ b/src/Contracts/TaskDetails/TaskDeletionDetails.php @@ -0,0 +1,38 @@ + + */ +final class TaskDeletionDetails implements TaskDetails +{ + /** + * @param non-negative-int|null $matchedTasks The number of matched tasks. If the API key used for the request doesn’t have access to an index, tasks relating to that index will not be included in matchedTasks. + * @param non-negative-int|null $canceledTasks The number of tasks successfully canceled. If the task cancellation fails, this will be 0. null when the task status is enqueued or processing. + * @param string|null $originalFilter the filter used in the delete task request + */ + public function __construct( + public readonly ?int $matchedTasks, + public readonly ?int $canceledTasks, + public readonly ?string $originalFilter, + ) { + } + + public static function fromArray(array $data): self + { + return new self( + $data['matchedTasks'], + $data['canceledTasks'], + $data['originalFilter'], + ); + } +} diff --git a/src/Contracts/TaskError.php b/src/Contracts/TaskError.php new file mode 100644 index 00000000..66696bdd --- /dev/null +++ b/src/Contracts/TaskError.php @@ -0,0 +1,40 @@ + 'detail'], - error: [ - 'message' => 'Index `documents` not found.', - 'code' => 'index_not_found', - 'type' => 'invalid_request', - 'link' => 'https://docs.meilisearch.com/errors#index_not_found', - ], + details: new IndexCreationDetails('custom_id'), + error: new TaskError( + 'Index `documents` not found.', + 'index_not_found', + 'invalid_request', + 'https://docs.meilisearch.com/errors#index_not_found', + ), data: [ 'taskUid' => 1, 'indexUid' => 'documents', @@ -51,13 +53,13 @@ public function testCreate(): void self::assertSame('PT0.184408715S', $task->getDuration()); self::assertSame(123, $task->getCanceledBy()); self::assertSame(666, $task->getBatchUid()); - self::assertSame(['some' => 'detail'], $task->getDetails()); - self::assertSame([ - 'message' => 'Index `documents` not found.', - 'code' => 'index_not_found', - 'type' => 'invalid_request', - 'link' => 'https://docs.meilisearch.com/errors#index_not_found', - ], $task->getError()); + self::assertEquals(new IndexCreationDetails('custom_id'), $task->getDetails()); + self::assertEquals(new TaskError( + 'Index `documents` not found.', + 'index_not_found', + 'invalid_request', + 'https://docs.meilisearch.com/errors#index_not_found', + ), $task->getError()); // Ensure the class supports array access retrocompatibility self::assertSame(1, $task['taskUid']); @@ -96,7 +98,7 @@ public function testArraySetThrows(): void $task = MockTask::create(TaskType::IndexCreation); $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Setting data on "MeiliSearch\Contracts\Task::type" is not supported.'); + $this->expectExceptionMessage('Setting data on "Meilisearch\Contracts\Task::type" is not supported.'); $task['type'] = TaskType::IndexDeletion; } @@ -106,7 +108,7 @@ public function testArrayUnsetThrows(): void $task = MockTask::create(TaskType::IndexCreation); $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Unsetting data on "MeiliSearch\Contracts\Task::type" is not supported.'); + $this->expectExceptionMessage('Unsetting data on "Meilisearch\Contracts\Task::type" is not supported.'); unset($task['type']); } diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 1d9e4fac..7ba897a8 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -6,8 +6,8 @@ use Meilisearch\Contracts\DocumentsQuery; use Meilisearch\Contracts\Http; -use MeiliSearch\Contracts\Task; -use MeiliSearch\Contracts\TaskType; +use Meilisearch\Contracts\Task; +use Meilisearch\Contracts\TaskType; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\ApiException; use Meilisearch\Exceptions\InvalidResponseBodyException; diff --git a/tests/Endpoints/DumpTest.php b/tests/Endpoints/DumpTest.php index fa17d4b2..33bc2d03 100644 --- a/tests/Endpoints/DumpTest.php +++ b/tests/Endpoints/DumpTest.php @@ -4,7 +4,7 @@ namespace Tests\Endpoints; -use MeiliSearch\Contracts\TaskType; +use Meilisearch\Contracts\TaskType; use Tests\TestCase; final class DumpTest extends TestCase diff --git a/tests/Endpoints/SnapshotsTest.php b/tests/Endpoints/SnapshotsTest.php index 8a1cad9f..e838491a 100644 --- a/tests/Endpoints/SnapshotsTest.php +++ b/tests/Endpoints/SnapshotsTest.php @@ -4,7 +4,7 @@ namespace Tests\Endpoints; -use MeiliSearch\Contracts\TaskType; +use Meilisearch\Contracts\TaskType; use Tests\TestCase; final class SnapshotsTest extends TestCase diff --git a/tests/MockTask.php b/tests/MockTask.php index c4823978..cd5e3b92 100644 --- a/tests/MockTask.php +++ b/tests/MockTask.php @@ -4,9 +4,9 @@ namespace Tests; -use MeiliSearch\Contracts\Task; -use MeiliSearch\Contracts\TaskStatus; -use MeiliSearch\Contracts\TaskType; +use Meilisearch\Contracts\Task; +use Meilisearch\Contracts\TaskStatus; +use Meilisearch\Contracts\TaskType; final class MockTask { diff --git a/tests/Settings/EmbeddersTest.php b/tests/Settings/EmbeddersTest.php index 8bfd7eab..091bc3cb 100644 --- a/tests/Settings/EmbeddersTest.php +++ b/tests/Settings/EmbeddersTest.php @@ -4,7 +4,7 @@ namespace Tests\Settings; -use MeiliSearch\Contracts\TaskStatus; +use Meilisearch\Contracts\TaskStatus; use Meilisearch\Endpoints\Indexes; use Meilisearch\Http\Client; use Tests\TestCase; From a1d56541103cfc28dd13ff7f23d4f801930d3731 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 12:49:52 +0300 Subject: [PATCH 17/51] Wrap in Task `Indexes::getTask` --- src/Endpoints/Indexes.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index 264e4b9c..64869027 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -157,9 +157,9 @@ public function swapIndexes(array $indexes): Task // Tasks - public function getTask(int $uid): array + public function getTask(int $uid): Task { - return $this->http->get('/tasks/'.$uid); + return Task::fromArray($this->http->get('/tasks/'.$uid)); } public function getTasks(?TasksQuery $options = null): TasksResults From 18813de306caf409d4d49872d5b7e78db52c281d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 13:35:53 +0300 Subject: [PATCH 18/51] Rename `$promise` to `$task` in tests --- tests/Endpoints/DocumentsTest.php | 164 ++++++++++---------- tests/Endpoints/FacetSearchTest.php | 4 +- tests/Endpoints/IndexTest.php | 38 ++--- tests/Endpoints/MultiSearchTest.php | 8 +- tests/Endpoints/SearchNestedFieldsTest.php | 4 +- tests/Endpoints/SearchTest.php | 24 +-- tests/Endpoints/TasksTest.php | 32 ++-- tests/Endpoints/TenantTokenTest.php | 16 +- tests/Settings/DisplayedAttributesTest.php | 12 +- tests/Settings/DistinctAttributeTest.php | 12 +- tests/Settings/EmbeddersTest.php | 16 +- tests/Settings/FacetSearchTest.php | 12 +- tests/Settings/FacetingAttributesTest.php | 12 +- tests/Settings/FilterableAttributesTest.php | 20 +-- tests/Settings/LocalizedAttributesTest.php | 12 +- tests/Settings/NonSeparatorTokensTest.php | 8 +- tests/Settings/PaginationTest.php | 12 +- tests/Settings/PrefixSearchTest.php | 12 +- tests/Settings/ProximityPrecisionTest.php | 12 +- tests/Settings/RankingRulesTest.php | 8 +- tests/Settings/SearchCutoffMsTest.php | 12 +- tests/Settings/SearchableAttributesTest.php | 8 +- tests/Settings/SeparatorTokensTest.php | 8 +- tests/Settings/SettingsTest.php | 20 +-- tests/Settings/SortableAttributesTest.php | 12 +- tests/Settings/StopWordsTest.php | 12 +- tests/Settings/SynonymsTest.php | 16 +- tests/Settings/TypoToleranceTest.php | 8 +- tests/Settings/WordDictionaryTest.php | 8 +- 29 files changed, 271 insertions(+), 271 deletions(-) diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 7ba897a8..4a0b83eb 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -21,9 +21,9 @@ final class DocumentsTest extends TestCase public function testAddDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $promise = $index->addDocuments(self::DOCUMENTS); + $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); } @@ -31,12 +31,12 @@ public function testAddDocuments(): void public function testAddDocumentsInBatches(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $promises = $index->addDocumentsInBatches(self::DOCUMENTS, 2); + $tasks = $index->addDocumentsInBatches(self::DOCUMENTS, 2); - self::assertCount(4, $promises); + self::assertCount(4, $tasks); - foreach ($promises as $promise) { - $index->waitForTask($promise['taskUid']); + foreach ($tasks as $task) { + $index->waitForTask($task['taskUid']); } $response = $index->getDocuments(); @@ -52,9 +52,9 @@ public function testAddDocumentWithSpecialChars(): void ]; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $promise = $index->addDocuments($documents); + $task = $index->addDocuments($documents); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(\count($documents), $response); @@ -73,9 +73,9 @@ public function testAddDocumentsCsv(): void $documentCsv = fread($fileCsv, filesize('./tests/datasets/songs.csv')); fclose($fileCsv); - $promise = $index->addDocumentsCsv($documentCsv); + $task = $index->addDocumentsCsv($documentCsv); - $update = $index->waitForTask($promise['taskUid']); + $update = $index->waitForTask($task['taskUid']); self::assertSame('succeeded', $update['status']); self::assertNotSame(0, $update['details']['receivedDocuments']); @@ -90,9 +90,9 @@ public function testAddDocumentsCsvWithCustomSeparator(): void $csv = file_get_contents('./tests/datasets/songs-custom-separator.csv', true); - $promise = $index->addDocumentsCsv($csv, null, '|'); + $task = $index->addDocumentsCsv($csv, null, '|'); - $update = $index->waitForTask($promise['taskUid']); + $update = $index->waitForTask($task['taskUid']); self::assertSame('succeeded', $update['status']); self::assertSame(6, $update['details']['receivedDocuments']); @@ -110,9 +110,9 @@ public function testAddDocumentsJson(): void $documentJson = fread($fileJson, filesize('./tests/datasets/small_movies.json')); fclose($fileJson); - $promise = $index->addDocumentsJson($documentJson); + $task = $index->addDocumentsJson($documentJson); - $update = $index->waitForTask($promise['taskUid']); + $update = $index->waitForTask($task['taskUid']); self::assertSame('succeeded', $update['status']); self::assertNotSame(0, $update['details']['receivedDocuments']); @@ -129,9 +129,9 @@ public function testAddDocumentsNdJson(): void $documentNdJson = fread($fileNdJson, filesize('./tests/datasets/songs.ndjson')); fclose($fileNdJson); - $promise = $index->addDocumentsNdjson($documentNdJson); + $task = $index->addDocumentsNdjson($documentNdJson); - $update = $index->waitForTask($promise['taskUid']); + $update = $index->waitForTask($task['taskUid']); self::assertSame('succeeded', $update['status']); self::assertNotSame(0, $update['details']['receivedDocuments']); @@ -224,15 +224,15 @@ public function testReplaceDocuments(): void public function testUpdateDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $promise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task['taskUid']); $replacement = [ 'id' => 456, 'title' => 'The Little Prince', ]; - $promise = $index->updateDocuments([$replacement]); + $task = $index->updateDocuments([$replacement]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocument($replacement['id']); self::assertSame($replacement['id'], $response['id']); @@ -258,11 +258,11 @@ public function testUpdateDocumentsInBatches(): void ['id' => 4, 'title' => 'Harry Potter and the Half-Blood Princess'], ['id' => 456, 'title' => 'The Little Prince'], ]; - $promises = $index->updateDocumentsInBatches($replacements, 4); - self::assertCount(2, $promises); + $tasks = $index->updateDocumentsInBatches($replacements, 4); + self::assertCount(2, $tasks); - foreach ($promises as $promise) { - $index->waitForTask($promise['taskUid']); + foreach ($tasks as $task) { + $index->waitForTask($task['taskUid']); } foreach ($replacements as $replacement) { @@ -340,12 +340,12 @@ public function testAddDocumentsCsvInBatches(): void // Total number of lines excluding header $total = \count(preg_split("/\r\n|\n|\r/", trim($documentCsv))) - 1; - $promises = $index->addDocumentsCsvInBatches($documentCsv, 250); + $tasks = $index->addDocumentsCsvInBatches($documentCsv, 250); - self::assertCount(2, $promises); + self::assertCount(2, $tasks); - foreach ($promises as $promise) { - $index->waitForTask($promise['taskUid']); + foreach ($tasks as $task) { + $index->waitForTask($task['taskUid']); } $response = $index->getDocuments(); @@ -396,12 +396,12 @@ public function testAddDocumentsNdjsonInBatches(): void $total = \count(preg_split("/\r\n|\n|\r/", trim($documentNdJson))); - $promises = $index->addDocumentsNdjsonInBatches($documentNdJson, 150); + $tasks = $index->addDocumentsNdjsonInBatches($documentNdJson, 150); - self::assertCount(2, $promises); + self::assertCount(2, $tasks); - foreach ($promises as $promise) { - $index->waitForTask($promise['taskUid']); + foreach ($tasks as $task) { + $index->waitForTask($task['taskUid']); } $response = $index->getDocuments(); @@ -417,9 +417,9 @@ public function testAddWithUpdateDocuments(): void 'id' => 9, 'title' => '1984', ]; - $promise = $index->updateDocuments([$document]); + $task = $index->updateDocuments([$document]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocument($document['id']); self::assertSame($document['id'], $response['id']); @@ -438,9 +438,9 @@ public function testDeleteNonExistingDocument(): void $index->waitForTask($response['taskUid']); $documentId = 9; - $promise = $index->deleteDocument($documentId); + $task = $index->deleteDocument($documentId); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); @@ -454,9 +454,9 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsInteger(): void $index->waitForTask($response['taskUid']); $documentId = 123; - $promise = $index->deleteDocument($documentId); + $task = $index->deleteDocument($documentId); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS) - 1, $response); @@ -470,8 +470,8 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsString(): void $addDocumentResponse = $index->addDocuments([['id' => $stringDocumentId]]); $index->waitForTask($addDocumentResponse['taskUid']); - $promise = $index->deleteDocument($stringDocumentId); - $index->waitForTask($promise['taskUid']); + $task = $index->deleteDocument($stringDocumentId); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); @@ -484,9 +484,9 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsInteger(): void $response = $index->addDocuments(self::DOCUMENTS); $index->waitForTask($response['taskUid']); $documentIds = [1, 2]; - $promise = $index->deleteDocuments($documentIds); + $task = $index->deleteDocuments($documentIds); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS) - 2, $response); @@ -501,9 +501,9 @@ public function testDeleteMultipleDocumentsWithFilter(): void $index->updateFilterableAttributes(['id']); $filter = ['filter' => ['id > 0']]; - $promise = $index->deleteDocuments($filter); + $task = $index->deleteDocuments($filter); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertEmpty($response); @@ -542,8 +542,8 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsString(): void $addDocumentResponse = $index->addDocuments($documents); $index->waitForTask($addDocumentResponse['taskUid']); - $promise = $index->deleteDocuments(['myUniqueId1', 'myUniqueId3']); - $index->waitForTask($promise['taskUid']); + $task = $index->deleteDocuments(['myUniqueId1', 'myUniqueId3']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(1, $response); @@ -555,9 +555,9 @@ public function testDeleteAllDocuments(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $response = $index->addDocuments(self::DOCUMENTS); $index->waitForTask($response['taskUid']); - $promise = $index->deleteAllDocuments(); + $task = $index->deleteAllDocuments(); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(0, $response); @@ -601,9 +601,9 @@ public function testUpdateDocumentWithPrimaryKey(): void ], ]; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateDocuments($documents, 'unique'); + $task = $index->updateDocuments($documents, 'unique'); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); self::assertSame('unique', $index->fetchPrimaryKey()); self::assertCount(1, $index->getDocuments()); @@ -612,8 +612,8 @@ public function testUpdateDocumentWithPrimaryKey(): void public function testGetDocumentsWithPagination(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $promise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments((new DocumentsQuery())->setLimit(3)); @@ -624,8 +624,8 @@ public function testGetDocumentsWithFilter(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); $index->updateFilterableAttributes(['genre', 'id']); - $promise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments((new DocumentsQuery())->setFilter(['id > 100'])); @@ -680,10 +680,10 @@ public function testGetDocumentsWithVector(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $promise = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $index->waitForTask($promise['taskUid']); - $promise = $index->updateDocuments(self::VECTOR_MOVIES); - $index->waitForTask($promise['taskUid']); + $task = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); + $index->waitForTask($task['taskUid']); + $task = $index->updateDocuments(self::VECTOR_MOVIES); + $index->waitForTask($task['taskUid']); $response = $index->getDocuments(new DocumentsQuery()); self::assertArrayNotHasKey('_vectors', $response->getResults()[0]); @@ -724,8 +724,8 @@ public function testUpdateDocumentsJson(): void $documentJson = fread($fileJson, filesize('./tests/datasets/small_movies.json')); fclose($fileJson); - $promise = $index->addDocumentsJson($documentJson); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocumentsJson($documentJson); + $index->waitForTask($task['taskUid']); $replacement = [ [ @@ -734,8 +734,8 @@ public function testUpdateDocumentsJson(): void ], ]; - $promise = $index->updateDocumentsJson(json_encode($replacement)); - $index->waitForTask($promise['taskUid']); + $task = $index->updateDocumentsJson(json_encode($replacement)); + $index->waitForTask($task['taskUid']); $response = $index->getDocument($replacement[0]['id']); @@ -755,14 +755,14 @@ public function testUpdateDocumentsCsv(): void $documentCsv = fread($fileCsv, filesize('./tests/datasets/songs.csv')); fclose($fileCsv); - $promise = $index->addDocumentsCsv($documentCsv); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocumentsCsv($documentCsv); + $index->waitForTask($task['taskUid']); $replacement = 'id,title'.PHP_EOL; $replacement .= '888221515,Young folks'.PHP_EOL; - $promise = $index->updateDocumentsCsv($replacement); - $index->waitForTask($promise['taskUid']); + $task = $index->updateDocumentsCsv($replacement); + $index->waitForTask($task['taskUid']); $response = $index->getDocument(888221515); @@ -780,14 +780,14 @@ public function testUpdateDocumentsCsvWithDelimiter(): void $csv = file_get_contents('./tests/datasets/songs.csv', true); - $promise = $index->addDocumentsCsv($csv); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocumentsCsv($csv); + $index->waitForTask($task['taskUid']); $replacement = 'id|title'.PHP_EOL; $replacement .= '888221515|Young folks'.PHP_EOL; - $promise = $index->updateDocumentsCsv($replacement, null, '|'); - $index->waitForTask($promise['taskUid']); + $task = $index->updateDocumentsCsv($replacement, null, '|'); + $index->waitForTask($task['taskUid']); $response = $index->getDocument(888221515); @@ -803,14 +803,14 @@ public function testUpdateDocumentsNdjson(): void $documentNdJson = fread($fileNdJson, filesize('./tests/datasets/songs.ndjson')); fclose($fileNdJson); - $promise = $index->addDocumentsNdjson($documentNdJson); - $index->waitForTask($promise['taskUid']); + $task = $index->addDocumentsNdjson($documentNdJson); + $index->waitForTask($task['taskUid']); $replacement = json_encode(['id' => 412559401, 'title' => 'WASPTHOVEN']).PHP_EOL; $replacement .= json_encode(['id' => 70764404, 'artist' => 'Ailitp']).PHP_EOL; - $promise = $index->updateDocumentsNdjson($replacement); - $index->waitForTask($promise['taskUid']); + $task = $index->updateDocumentsNdjson($replacement); + $index->waitForTask($task['taskUid']); $response = $index->getDocument(412559401); self::assertSame(412559401, (int) $response['id']); @@ -838,10 +838,10 @@ public function testUpdateDocumentsCsvInBatches(): void $replacement .= '888221515,Young folks'.PHP_EOL; $replacement .= '235115704,Mister Klein'.PHP_EOL; - $promises = $index->updateDocumentsCsvInBatches($replacement, 1); - self::assertCount(2, $promises); - foreach ($promises as $promise) { - $index->waitForTask($promise['taskUid']); + $tasks = $index->updateDocumentsCsvInBatches($replacement, 1); + self::assertCount(2, $tasks); + foreach ($tasks as $task) { + $index->waitForTask($task['taskUid']); } $response = $index->getDocument(888221515); @@ -901,10 +901,10 @@ public function testUpdateDocumentsNdjsonInBatches(): void $replacement = json_encode(['id' => 412559401, 'title' => 'WASPTHOVEN']).PHP_EOL; $replacement .= json_encode(['id' => 70764404, 'artist' => 'Ailitp']).PHP_EOL; - $promises = $index->updateDocumentsNdjsonInBatches($replacement, 1); - self::assertCount(2, $promises); - foreach ($promises as $promise) { - $index->waitForTask($promise['taskUid']); + $tasks = $index->updateDocumentsNdjsonInBatches($replacement, 1); + self::assertCount(2, $tasks); + foreach ($tasks as $task) { + $index->waitForTask($task['taskUid']); } $response = $index->getDocument(412559401); diff --git a/tests/Endpoints/FacetSearchTest.php b/tests/Endpoints/FacetSearchTest.php index 21fdb8e0..a3f57cb7 100644 --- a/tests/Endpoints/FacetSearchTest.php +++ b/tests/Endpoints/FacetSearchTest.php @@ -18,8 +18,8 @@ protected function setUp(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateDocuments(self::DOCUMENTS); - $promise = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task['taskUid']); } public function testBasicSearchWithFilters(): void diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 40c0691f..7f7d7cf2 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -167,12 +167,12 @@ public function testGetAndFetchPrimaryKey(): void public function testGetTasks(): void { - $promise = $this->client->createIndex('new-index', ['primaryKey' => 'objectID']); - $this->index->waitForTask($promise['taskUid']); - $promise = $this->client->createIndex('other-index', ['primaryKey' => 'objectID']); - $this->index->waitForTask($promise['taskUid']); - $promise = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $this->index->waitForTask($promise['taskUid']); + $task = $this->client->createIndex('new-index', ['primaryKey' => 'objectID']); + $this->index->waitForTask($task['taskUid']); + $task = $this->client->createIndex('other-index', ['primaryKey' => 'objectID']); + $this->index->waitForTask($task['taskUid']); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); + $this->index->waitForTask($task['taskUid']); $tasks = $this->index->getTasks((new TasksQuery())->setIndexUids(['other-index'])); @@ -185,12 +185,12 @@ public function testGetTasks(): void public function testWaitForTaskDefault(): void { - $promise = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($promise['taskUid']); + $response = $this->index->waitForTask($task['taskUid']); self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $promise['taskUid']); + self::assertSame($response['uid'], $task['taskUid']); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('duration', $response); @@ -200,11 +200,11 @@ public function testWaitForTaskDefault(): void public function testWaitForTaskWithTimeoutAndInterval(): void { - $promise = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($promise['taskUid'], 100, 20); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); + $response = $this->index->waitForTask($task['taskUid'], 100, 20); self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $promise['taskUid']); + self::assertSame($response['uid'], $task['taskUid']); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('duration', $response); @@ -215,11 +215,11 @@ public function testWaitForTaskWithTimeoutAndInterval(): void public function testWaitForTaskWithTimeout(): void { - $promise = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($promise['taskUid'], 1000); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); + $response = $this->index->waitForTask($task['taskUid'], 1000); self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $promise['taskUid']); + self::assertSame($response['uid'], $task['taskUid']); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('duration', $response); @@ -257,8 +257,8 @@ public function testDeleteIndexes(): void public function testSwapIndexes(): void { - $promise = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']]); - $response = $this->client->waitForTask($promise['taskUid']); + $task = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']]); + $response = $this->client->waitForTask($task['taskUid']); self::assertSame(['indexA', 'indexB'], $response['details']['swaps'][0]['indexes']); self::assertSame(['indexC', 'indexD'], $response['details']['swaps'][1]['indexes']); @@ -268,8 +268,8 @@ public function testSwapIndexes(): void public function testDeleteTasks(): void { - $promise = $this->client->deleteTasks((new DeleteTasksQuery())->setUids([1, 2])); - $response = $this->client->waitForTask($promise['taskUid']); + $task = $this->client->deleteTasks((new DeleteTasksQuery())->setUids([1, 2])); + $response = $this->client->waitForTask($task['taskUid']); self::assertSame('?uids=1%2C2', $response['details']['originalFilter']); self::assertIsNumeric($response['details']['matchedTasks']); diff --git a/tests/Endpoints/MultiSearchTest.php b/tests/Endpoints/MultiSearchTest.php index 5935ac16..2b9062e4 100644 --- a/tests/Endpoints/MultiSearchTest.php +++ b/tests/Endpoints/MultiSearchTest.php @@ -25,8 +25,8 @@ protected function setUp(): void $this->booksIndex = $this->createEmptyIndex($this->safeIndexName('books')); $this->booksIndex->updateSortableAttributes(['author']); $this->booksIndex->updateFilterableAttributes(['genre']); - $promise = $this->booksIndex->updateDocuments(self::DOCUMENTS); - $this->booksIndex->waitForTask($promise['taskUid']); + $task = $this->booksIndex->updateDocuments(self::DOCUMENTS); + $this->booksIndex->waitForTask($task['taskUid']); $this->songsIndex = $this->createEmptyIndex($this->safeIndexName('songs')); $this->songsIndex->updateFilterableAttributes(['duration-float']); @@ -34,8 +34,8 @@ protected function setUp(): void $documents = fread($fileCsv, filesize('./tests/datasets/songs-custom-separator.csv')); fclose($fileCsv); - $promise = $this->songsIndex->addDocumentsCsv($documents, null, '|'); - $this->songsIndex->waitForTask($promise['taskUid']); + $task = $this->songsIndex->addDocumentsCsv($documents, null, '|'); + $this->songsIndex->waitForTask($task['taskUid']); } public function testSearchQueryData(): void diff --git a/tests/Endpoints/SearchNestedFieldsTest.php b/tests/Endpoints/SearchNestedFieldsTest.php index f98d6875..0be61df6 100644 --- a/tests/Endpoints/SearchNestedFieldsTest.php +++ b/tests/Endpoints/SearchNestedFieldsTest.php @@ -15,8 +15,8 @@ protected function setUp(): void { parent::setUp(); $this->index = $this->createEmptyIndex($this->safeIndexName('nestedIndex')); - $promise = $this->index->updateDocuments(self::NESTED_DOCUMENTS); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDocuments(self::NESTED_DOCUMENTS); + $this->index->waitForTask($task['taskUid']); } public function testBasicSearchOnNestedFields(): void diff --git a/tests/Endpoints/SearchTest.php b/tests/Endpoints/SearchTest.php index 4e131543..3c52a894 100644 --- a/tests/Endpoints/SearchTest.php +++ b/tests/Endpoints/SearchTest.php @@ -17,8 +17,8 @@ protected function setUp(): void { parent::setUp(); $this->index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $this->index->updateDocuments(self::DOCUMENTS); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDocuments(self::DOCUMENTS); + $this->index->waitForTask($task['taskUid']); } public function testBasicSearch(): void @@ -709,11 +709,11 @@ public function testVectorSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $index->waitForTask($promise['taskUid']); + $task = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); + $index->waitForTask($task['taskUid']); - $promise = $index->updateDocuments(self::VECTOR_MOVIES); - $index->waitForTask($promise['taskUid']); + $task = $index->updateDocuments(self::VECTOR_MOVIES); + $index->waitForTask($task['taskUid']); $response = $index->search('', ['vector' => [-0.5, 0.3, 0.85], 'hybrid' => ['semanticRatio' => 1.0, 'embedder' => 'manual']]); @@ -866,8 +866,8 @@ public function testSearchAndRetrieveFacetStats(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateFilterableAttributes(['info.reviewNb']); - $promise = $this->index->updateDocuments(self::NESTED_DOCUMENTS); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDocuments(self::NESTED_DOCUMENTS); + $this->index->waitForTask($task['taskUid']); $response = $this->index->search( null, @@ -882,8 +882,8 @@ public function testSearchWithDistinctAttribute(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateFilterableAttributes(['genre']); - $promise = $this->index->updateDocuments(self::DOCUMENTS); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDocuments(self::DOCUMENTS); + $this->index->waitForTask($task['taskUid']); $response = $this->index->search(null, [ 'distinct' => 'genre', @@ -912,8 +912,8 @@ public function testSearchWithLocales(): void { $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateDocuments(self::DOCUMENTS); - $promise = $this->index->updateLocalizedAttributes([['attributePatterns' => ['title', 'comment'], 'locales' => ['fra', 'eng']]]); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateLocalizedAttributes([['attributePatterns' => ['title', 'comment'], 'locales' => ['fra', 'eng']]]); + $this->index->waitForTask($task['taskUid']); $response = $this->index->search('french', [ 'locales' => ['fra', 'eng'], diff --git a/tests/Endpoints/TasksTest.php b/tests/Endpoints/TasksTest.php index 513f632e..696ae787 100644 --- a/tests/Endpoints/TasksTest.php +++ b/tests/Endpoints/TasksTest.php @@ -24,10 +24,10 @@ protected function setUp(): void public function testGetOneTaskFromWaitTask(): void { - [$promise, $response] = $this->seedIndex(); + [$task, $response] = $this->seedIndex(); self::assertArrayHasKey('status', $response); - self::assertSame($response['uid'], $promise['taskUid']); + self::assertSame($response['uid'], $task['taskUid']); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('indexUid', $response); @@ -40,11 +40,11 @@ public function testGetOneTaskFromWaitTask(): void public function testGetOneTaskClient(): void { - [$promise] = $this->seedIndex(); + [$task] = $this->seedIndex(); - $response = $this->client->getTask($promise['taskUid']); + $response = $this->client->getTask($task['taskUid']); self::assertArrayHasKey('status', $response); - self::assertSame($response['uid'], $promise['taskUid']); + self::assertSame($response['uid'], $task['taskUid']); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('indexUid', $response); @@ -76,8 +76,8 @@ public function testGetAllTasksClientWithPagination(): void public function getAllTasksClientWithBatchFilter(): void { - [$promise] = $this->seedIndex(); - $task = $this->client->getTask($promise['taskUid']); + [$task] = $this->seedIndex(); + $task = $this->client->getTask($task['taskUid']); $response = $this->client->getTasks((new TasksQuery()) ->setBatchUid($task['uid']) @@ -88,11 +88,11 @@ public function getAllTasksClientWithBatchFilter(): void public function testGetOneTaskIndex(): void { - [$promise] = $this->seedIndex(); + [$task] = $this->seedIndex(); - $response = $this->index->getTask($promise['taskUid']); + $response = $this->index->getTask($task['taskUid']); self::assertArrayHasKey('status', $response); - self::assertSame($response['uid'], $promise['taskUid']); + self::assertSame($response['uid'], $task['taskUid']); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('indexUid', $response); @@ -139,10 +139,10 @@ public function testCancelTasksWithFilter(): void { $date = new \DateTime('yesterday'); $query = http_build_query(['afterEnqueuedAt' => $date->format(\DateTime::RFC3339)]); - $promise = $this->client->cancelTasks((new CancelTasksQuery())->setAfterEnqueuedAt($date)); + $task = $this->client->cancelTasks((new CancelTasksQuery())->setAfterEnqueuedAt($date)); - self::assertSame('taskCancelation', $promise['type']); - $response = $this->client->waitForTask($promise['taskUid']); + self::assertSame('taskCancelation', $task['type']); + $response = $this->client->waitForTask($task['taskUid']); self::assertSame('?'.$query, $response['details']['originalFilter']); self::assertSame('taskCancelation', $response['type']); @@ -173,9 +173,9 @@ public function testExceptionIfNoTaskIdWhenGetting(): void private function seedIndex(): array { - $promise = $this->index->updateDocuments(self::DOCUMENTS); - $response = $this->client->waitForTask($promise['taskUid']); + $task = $this->index->updateDocuments(self::DOCUMENTS); + $response = $this->client->waitForTask($task['taskUid']); - return [$promise, $response]; + return [$task, $response]; } } diff --git a/tests/Endpoints/TenantTokenTest.php b/tests/Endpoints/TenantTokenTest.php index 6c8f942f..c6fe0def 100644 --- a/tests/Endpoints/TenantTokenTest.php +++ b/tests/Endpoints/TenantTokenTest.php @@ -42,8 +42,8 @@ protected function tearDown(): void public function testGenerateTenantTokenWithSearchRulesOnly(): void { - $promise = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($promise['taskUid']); + $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); + $this->client->waitForTask($task['taskUid']); $token = $this->privateClient->generateTenantToken($this->key->getUid(), ['*']); $tokenClient = new Client($this->host, $token); @@ -55,8 +55,8 @@ public function testGenerateTenantTokenWithSearchRulesOnly(): void public function testGenerateTenantTokenWithSearchRulesAsObject(): void { - $promise = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($promise['taskUid']); + $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); + $this->client->waitForTask($task['taskUid']); $token = $this->privateClient->generateTenantToken($this->key->getUid(), (object) ['*' => (object) []]); $tokenClient = new Client($this->host, $token); @@ -68,12 +68,12 @@ public function testGenerateTenantTokenWithSearchRulesAsObject(): void public function testGenerateTenantTokenWithFilter(): void { - $promise = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($promise['taskUid']); - $promiseFromFilter = $this->client->index('tenantToken')->updateFilterableAttributes([ + $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); + $this->client->waitForTask($task['taskUid']); + $taskFromFilter = $this->client->index('tenantToken')->updateFilterableAttributes([ 'id', ]); - $this->client->waitForTask($promiseFromFilter['taskUid']); + $this->client->waitForTask($taskFromFilter['taskUid']); $token = $this->privateClient->generateTenantToken($this->key->getUid(), (object) ['tenantToken' => (object) ['filter' => 'id > 10']]); $tokenClient = new Client($this->host, $token); diff --git a/tests/Settings/DisplayedAttributesTest.php b/tests/Settings/DisplayedAttributesTest.php index 31c03bf9..31f3272e 100644 --- a/tests/Settings/DisplayedAttributesTest.php +++ b/tests/Settings/DisplayedAttributesTest.php @@ -25,9 +25,9 @@ public function testUpdateDisplayedAttributes(): void $newAttributes = ['title']; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateDisplayedAttributes($newAttributes); + $task = $index->updateDisplayedAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $displayedAttributes = $index->getDisplayedAttributes(); @@ -39,12 +39,12 @@ public function testResetDisplayedAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = ['title']; - $promise = $index->updateDisplayedAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateDisplayedAttributes($newAttributes); + $index->waitForTask($task['taskUid']); - $promise = $index->resetDisplayedAttributes(); + $task = $index->resetDisplayedAttributes(); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $displayedAttributes = $index->getDisplayedAttributes(); self::assertSame(['*'], $displayedAttributes); diff --git a/tests/Settings/DistinctAttributeTest.php b/tests/Settings/DistinctAttributeTest.php index 2461d50c..7fcac32b 100644 --- a/tests/Settings/DistinctAttributeTest.php +++ b/tests/Settings/DistinctAttributeTest.php @@ -28,8 +28,8 @@ public function testUpdateDistinctAttribute(): void { $distinctAttribute = 'description'; - $promise = $this->index->updateDistinctAttribute($distinctAttribute); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDistinctAttribute($distinctAttribute); + $this->index->waitForTask($task['taskUid']); self::assertSame($distinctAttribute, $this->index->getDistinctAttribute()); } @@ -38,11 +38,11 @@ public function testResetDistinctAttribute(): void { $distinctAttribute = 'description'; - $promise = $this->index->updateDistinctAttribute($distinctAttribute); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDistinctAttribute($distinctAttribute); + $this->index->waitForTask($task['taskUid']); - $promise = $this->index->resetDistinctAttribute(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetDistinctAttribute(); + $this->index->waitForTask($task['taskUid']); self::assertNull($this->index->getDistinctAttribute()); } diff --git a/tests/Settings/EmbeddersTest.php b/tests/Settings/EmbeddersTest.php index 091bc3cb..02097998 100644 --- a/tests/Settings/EmbeddersTest.php +++ b/tests/Settings/EmbeddersTest.php @@ -32,17 +32,17 @@ public function testUpdateEmbedders(): void { $newEmbedders = ['manual' => ['source' => 'userProvided', 'dimensions' => 3, 'binaryQuantized' => true]]; - $promise = $this->index->updateEmbedders($newEmbedders); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateEmbedders($newEmbedders); + $this->index->waitForTask($task['taskUid']); self::assertSame($newEmbedders, $this->index->getEmbedders()); } public function testResetEmbedders(): void { - $promise = $this->index->resetEmbedders(); + $task = $this->index->resetEmbedders(); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); self::assertSame(self::DEFAULT_EMBEDDER, $this->index->getEmbedders()); } @@ -55,7 +55,7 @@ public function testHuggingFacePooling(): void 'pooling' => 'useModel', ]; - $promise = $this->index->updateEmbedders([ + $task = $this->index->updateEmbedders([ 'embedder_name' => [ 'source' => 'huggingFace', 'model' => 'sentence-transformers/all-MiniLM-L6-v2', @@ -63,7 +63,7 @@ public function testHuggingFacePooling(): void ], ]); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); $embedders = $this->index->getEmbedders(); @@ -89,10 +89,10 @@ public function testCompositeEmbedder(): void ], ]; - $promise = $this->index->updateEmbedders([ + $task = $this->index->updateEmbedders([ 'embedder_name' => $embedder, ]); - self::assertSame(TaskStatus::Enqueued, $promise->getStatus()); + self::assertSame(TaskStatus::Enqueued, $task->getStatus()); } } diff --git a/tests/Settings/FacetSearchTest.php b/tests/Settings/FacetSearchTest.php index f4df97b8..78634f51 100644 --- a/tests/Settings/FacetSearchTest.php +++ b/tests/Settings/FacetSearchTest.php @@ -21,8 +21,8 @@ public function testUpdateFacetSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateFacetSearch(false); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFacetSearch(false); + $index->waitForTask($task['taskUid']); self::assertFalse($index->getFacetSearch()); } @@ -31,11 +31,11 @@ public function testResetFacetSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateFacetSearch(false); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFacetSearch(false); + $index->waitForTask($task['taskUid']); - $promise = $index->resetFacetSearch(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetFacetSearch(); + $index->waitForTask($task['taskUid']); self::assertTrue($index->getFacetSearch()); } diff --git a/tests/Settings/FacetingAttributesTest.php b/tests/Settings/FacetingAttributesTest.php index 4bc1f82b..b7e740cf 100644 --- a/tests/Settings/FacetingAttributesTest.php +++ b/tests/Settings/FacetingAttributesTest.php @@ -25,8 +25,8 @@ public function testUpdateFacetingAttributes(): void $newAttributes = ['sortFacetValuesBy' => ['*' => 'count']]; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateFaceting($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFaceting($newAttributes); + $index->waitForTask($task['taskUid']); self::assertSame([ 'maxValuesPerFacet' => 100, @@ -39,11 +39,11 @@ public function testResetFaceting(): void $newAttributes = ['sortFacetValuesBy' => ['*' => 'count']]; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateFaceting($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFaceting($newAttributes); + $index->waitForTask($task['taskUid']); - $promise = $index->resetFaceting(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetFaceting(); + $index->waitForTask($task['taskUid']); self::assertSame([ 'maxValuesPerFacet' => 100, diff --git a/tests/Settings/FilterableAttributesTest.php b/tests/Settings/FilterableAttributesTest.php index ba88a8c6..c31979d1 100644 --- a/tests/Settings/FilterableAttributesTest.php +++ b/tests/Settings/FilterableAttributesTest.php @@ -20,8 +20,8 @@ public function testUpdateFilterableAttributes(): void $expectedAttributes = ['title']; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateFilterableAttributes($expectedAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFilterableAttributes($expectedAttributes); + $index->waitForTask($task['taskUid']); self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } @@ -31,11 +31,11 @@ public function testResetFilterableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = ['title']; - $promise = $index->updateFilterableAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFilterableAttributes($newAttributes); + $index->waitForTask($task['taskUid']); - $promise = $index->resetFilterableAttributes(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetFilterableAttributes(); + $index->waitForTask($task['taskUid']); self::assertEmpty($index->getFilterableAttributes()); } @@ -58,8 +58,8 @@ public function testUpdateGranularFilterableAttributes(): void ], ]; - $promise = $index->updateFilterableAttributes($expectedAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateFilterableAttributes($expectedAttributes); + $index->waitForTask($task['taskUid']); self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } @@ -68,13 +68,13 @@ public function testUpdateGeoWithGranularFilterableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateFilterableAttributes([ + $task = $index->updateFilterableAttributes([ [ 'attributePatterns' => ['_geo'], ], ]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); self::assertSame([ [ diff --git a/tests/Settings/LocalizedAttributesTest.php b/tests/Settings/LocalizedAttributesTest.php index 68fc5851..b38966e4 100644 --- a/tests/Settings/LocalizedAttributesTest.php +++ b/tests/Settings/LocalizedAttributesTest.php @@ -25,9 +25,9 @@ public function testUpdateLocalizedAttributes(): void $newAttributes = [['attributePatterns' => ['doggo'], 'locales' => ['fra']]]; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateLocalizedAttributes($newAttributes); + $task = $index->updateLocalizedAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $localizedAttributes = $index->getLocalizedAttributes(); @@ -39,11 +39,11 @@ public function testResetLocalizedAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = [['attributePatterns' => ['doggo'], 'locales' => ['fra']]]; - $promise = $index->updateLocalizedAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateLocalizedAttributes($newAttributes); + $index->waitForTask($task['taskUid']); - $promise = $index->resetLocalizedAttributes(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetLocalizedAttributes(); + $index->waitForTask($task['taskUid']); $localizedAttributes = $index->getLocalizedAttributes(); self::assertNull($localizedAttributes); diff --git a/tests/Settings/NonSeparatorTokensTest.php b/tests/Settings/NonSeparatorTokensTest.php index 6a4e1ac3..78fc12f1 100644 --- a/tests/Settings/NonSeparatorTokensTest.php +++ b/tests/Settings/NonSeparatorTokensTest.php @@ -34,16 +34,16 @@ public function testUpdateNonSeparatorTokens(): void '|', ]; - $promise = $this->index->updateNonSeparatorTokens($newNonSeparatorTokens); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateNonSeparatorTokens($newNonSeparatorTokens); + $this->index->waitForTask($task['taskUid']); self::assertSame($newNonSeparatorTokens, $this->index->getNonSeparatorTokens()); } public function testResetNonSeparatorTokens(): void { - $promise = $this->index->resetNonSeparatorTokens(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetNonSeparatorTokens(); + $this->index->waitForTask($task['taskUid']); self::assertSame(self::DEFAULT_NON_SEPARATOR_TOKENS, $this->index->getNonSeparatorTokens()); } diff --git a/tests/Settings/PaginationTest.php b/tests/Settings/PaginationTest.php index 7193af85..b106de9e 100644 --- a/tests/Settings/PaginationTest.php +++ b/tests/Settings/PaginationTest.php @@ -30,21 +30,21 @@ public function testGetDefaultPagination(): void public function testUpdatePagination(): void { - $promise = $this->index->updatePagination(['maxTotalHits' => 100]); + $task = $this->index->updatePagination(['maxTotalHits' => 100]); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); self::assertSame(['maxTotalHits' => 100], $this->index->getPagination()); } public function testResetPagination(): void { - $promise = $this->index->updatePagination(['maxTotalHits' => 100]); + $task = $this->index->updatePagination(['maxTotalHits' => 100]); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); - $promise = $this->index->resetPagination(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetPagination(); + $this->index->waitForTask($task['taskUid']); self::assertSame(self::DEFAULT_PAGINATION, $this->index->getPagination()); } diff --git a/tests/Settings/PrefixSearchTest.php b/tests/Settings/PrefixSearchTest.php index 7ceb633d..babe9d76 100644 --- a/tests/Settings/PrefixSearchTest.php +++ b/tests/Settings/PrefixSearchTest.php @@ -21,8 +21,8 @@ public function testUpdatePrefixSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updatePrefixSearch('disabled'); - $index->waitForTask($promise['taskUid']); + $task = $index->updatePrefixSearch('disabled'); + $index->waitForTask($task['taskUid']); self::assertSame('disabled', $index->getPrefixSearch()); } @@ -31,11 +31,11 @@ public function testResetPrefixSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updatePrefixSearch('disabled'); - $index->waitForTask($promise['taskUid']); + $task = $index->updatePrefixSearch('disabled'); + $index->waitForTask($task['taskUid']); - $promise = $index->resetPrefixSearch(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetPrefixSearch(); + $index->waitForTask($task['taskUid']); self::assertSame('indexingTime', $index->getPrefixSearch()); } diff --git a/tests/Settings/ProximityPrecisionTest.php b/tests/Settings/ProximityPrecisionTest.php index 85018008..67a4529d 100644 --- a/tests/Settings/ProximityPrecisionTest.php +++ b/tests/Settings/ProximityPrecisionTest.php @@ -26,19 +26,19 @@ public function testGetDefaultProximityPrecision(): void public function testUpdateProximityPrecision(): void { - $promise = $this->index->updateProximityPrecision('byAttribute'); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateProximityPrecision('byAttribute'); + $this->index->waitForTask($task['taskUid']); self::assertSame('byAttribute', $this->index->getProximityPrecision()); } public function testResetProximityPrecision(): void { - $promise = $this->index->updateProximityPrecision('byAttribute'); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateProximityPrecision('byAttribute'); + $this->index->waitForTask($task['taskUid']); - $promise = $this->index->resetProximityPrecision(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetProximityPrecision(); + $this->index->waitForTask($task['taskUid']); self::assertSame('byWord', $this->index->getProximityPrecision()); } diff --git a/tests/Settings/RankingRulesTest.php b/tests/Settings/RankingRulesTest.php index 896f71ce..b5ad816e 100644 --- a/tests/Settings/RankingRulesTest.php +++ b/tests/Settings/RankingRulesTest.php @@ -41,9 +41,9 @@ public function testUpdateRankingRules(): void 'description:desc', ]; - $promise = $this->index->updateRankingRules($newRankingRules); + $task = $this->index->updateRankingRules($newRankingRules); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); $rankingRules = $this->index->getRankingRules(); @@ -52,9 +52,9 @@ public function testUpdateRankingRules(): void public function testResetRankingRules(): void { - $promise = $this->index->resetRankingRules(); + $task = $this->index->resetRankingRules(); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); $rankingRules = $this->index->getRankingRules(); self::assertSame(self::DEFAULT_RANKING_RULES, $rankingRules); diff --git a/tests/Settings/SearchCutoffMsTest.php b/tests/Settings/SearchCutoffMsTest.php index 3d941168..4f8c6c00 100644 --- a/tests/Settings/SearchCutoffMsTest.php +++ b/tests/Settings/SearchCutoffMsTest.php @@ -26,19 +26,19 @@ public function testGetDefaultSearchCutoffMs(): void public function testUpdateSearchCutoffMs(): void { - $promise = $this->index->updateSearchCutoffMs(50); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateSearchCutoffMs(50); + $this->index->waitForTask($task['taskUid']); self::assertSame(50, $this->index->getSearchCutoffMs()); } public function testResetSearchCutoffMs(): void { - $promise = $this->index->updateSearchCutoffMs(50); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateSearchCutoffMs(50); + $this->index->waitForTask($task['taskUid']); - $promise = $this->index->resetSearchCutoffMs(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetSearchCutoffMs(); + $this->index->waitForTask($task['taskUid']); self::assertNull($this->index->getSearchCutoffMs()); } diff --git a/tests/Settings/SearchableAttributesTest.php b/tests/Settings/SearchableAttributesTest.php index 361d67f1..7f0515fc 100644 --- a/tests/Settings/SearchableAttributesTest.php +++ b/tests/Settings/SearchableAttributesTest.php @@ -28,8 +28,8 @@ public function testUpdateSearchableAttributes(): void 'description', ]; - $promise = $indexA->updateSearchableAttributes($searchableAttributes); - $indexA->waitForTask($promise['taskUid']); + $task = $indexA->updateSearchableAttributes($searchableAttributes); + $indexA->waitForTask($task['taskUid']); self::assertSame($searchableAttributes, $indexA->getSearchableAttributes()); } @@ -38,8 +38,8 @@ public function testResetSearchableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName('books-1')); - $promise = $index->resetSearchableAttributes(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetSearchableAttributes(); + $index->waitForTask($task['taskUid']); self::assertSame(['*'], $index->getSearchableAttributes()); } diff --git a/tests/Settings/SeparatorTokensTest.php b/tests/Settings/SeparatorTokensTest.php index 185fd890..c61c16ba 100644 --- a/tests/Settings/SeparatorTokensTest.php +++ b/tests/Settings/SeparatorTokensTest.php @@ -34,16 +34,16 @@ public function testUpdateSeparatorTokens(): void '|', ]; - $promise = $this->index->updateSeparatorTokens($newSeparatorTokens); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateSeparatorTokens($newSeparatorTokens); + $this->index->waitForTask($task['taskUid']); self::assertSame($newSeparatorTokens, $this->index->getSeparatorTokens()); } public function testResetSeparatorTokens(): void { - $promise = $this->index->resetSeparatorTokens(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetSeparatorTokens(); + $this->index->waitForTask($task['taskUid']); self::assertSame(self::DEFAULT_SEPARATOR_TOKENS, $this->index->getSeparatorTokens()); } diff --git a/tests/Settings/SettingsTest.php b/tests/Settings/SettingsTest.php index ea062690..aa246e11 100644 --- a/tests/Settings/SettingsTest.php +++ b/tests/Settings/SettingsTest.php @@ -85,14 +85,14 @@ public function testUpdateSettings(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateSettings([ + $task = $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], 'facetSearch' => false, 'prefixSearch' => 'disabled', ]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $settings = $index->getSettings(); @@ -129,18 +129,18 @@ public function testUpdateSettingsWithoutOverwritingThem(): void $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateSettings([ + $task = $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], 'typoTolerance' => $new_typo_tolerance, ]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); - $promise = $index->updateSettings([ + $task = $index->updateSettings([ 'searchableAttributes' => ['title'], ]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); $settings = $index->getSettings(); @@ -163,15 +163,15 @@ public function testResetSettings(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateSettings([ + $task = $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], ]); - $index->waitForTask($promise['taskUid']); + $index->waitForTask($task['taskUid']); - $promise = $index->resetSettings(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetSettings(); + $index->waitForTask($task['taskUid']); $settings = $index->getSettings(); diff --git a/tests/Settings/SortableAttributesTest.php b/tests/Settings/SortableAttributesTest.php index f241dc3f..673fa647 100644 --- a/tests/Settings/SortableAttributesTest.php +++ b/tests/Settings/SortableAttributesTest.php @@ -20,8 +20,8 @@ public function testUpdateSortableAttributes(): void $newAttributes = ['title']; $index = $this->createEmptyIndex($this->safeIndexName()); - $promise = $index->updateSortableAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateSortableAttributes($newAttributes); + $index->waitForTask($task['taskUid']); self::assertSame($newAttributes, $index->getSortableAttributes()); } @@ -31,11 +31,11 @@ public function testResetSortableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = ['title']; - $promise = $index->updateSortableAttributes($newAttributes); - $index->waitForTask($promise['taskUid']); + $task = $index->updateSortableAttributes($newAttributes); + $index->waitForTask($task['taskUid']); - $promise = $index->resetSortableAttributes(); - $index->waitForTask($promise['taskUid']); + $task = $index->resetSortableAttributes(); + $index->waitForTask($task['taskUid']); self::assertEmpty($index->getSortableAttributes()); } diff --git a/tests/Settings/StopWordsTest.php b/tests/Settings/StopWordsTest.php index cb823cc7..447b3ba7 100644 --- a/tests/Settings/StopWordsTest.php +++ b/tests/Settings/StopWordsTest.php @@ -27,20 +27,20 @@ public function testGetDefaultStopWords(): void public function testUpdateStopWords(): void { $newStopWords = ['the']; - $promise = $this->index->updateStopWords($newStopWords); + $task = $this->index->updateStopWords($newStopWords); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); self::assertSame($newStopWords, $this->index->getStopWords()); } public function testResetStopWords(): void { - $promise = $this->index->updateStopWords(['the']); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateStopWords(['the']); + $this->index->waitForTask($task['taskUid']); - $promise = $this->index->resetStopWords(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetStopWords(); + $this->index->waitForTask($task['taskUid']); self::assertEmpty($this->index->getStopWords()); } diff --git a/tests/Settings/SynonymsTest.php b/tests/Settings/SynonymsTest.php index 7fb02361..1c58c746 100644 --- a/tests/Settings/SynonymsTest.php +++ b/tests/Settings/SynonymsTest.php @@ -28,8 +28,8 @@ public function testUpdateSynonyms(): void 'hp' => ['harry potter'], ]; - $promise = $this->index->updateSynonyms($newSynonyms); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateSynonyms($newSynonyms); + $this->index->waitForTask($task['taskUid']); self::assertSame($newSynonyms, $this->index->getSynonyms()); } @@ -38,21 +38,21 @@ public function testUpdateSynonymsWithEmptyArray(): void { $newSynonyms = []; - $promise = $this->index->updateSynonyms($newSynonyms); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateSynonyms($newSynonyms); + $this->index->waitForTask($task['taskUid']); self::assertSame($newSynonyms, $this->index->getSynonyms()); } public function testResetSynonyms(): void { - $promise = $this->index->updateSynonyms([ + $task = $this->index->updateSynonyms([ 'hp' => ['harry potter'], ]); - $this->index->waitForTask($promise['taskUid']); - $promise = $this->index->resetSynonyms(); + $this->index->waitForTask($task['taskUid']); + $task = $this->index->resetSynonyms(); - $this->index->waitForTask($promise['taskUid']); + $this->index->waitForTask($task['taskUid']); self::assertEmpty($this->index->getSynonyms()); } diff --git a/tests/Settings/TypoToleranceTest.php b/tests/Settings/TypoToleranceTest.php index 1f767392..ef4ea308 100644 --- a/tests/Settings/TypoToleranceTest.php +++ b/tests/Settings/TypoToleranceTest.php @@ -47,8 +47,8 @@ public function testUpdateTypoTolerance(): void 'disableOnAttributes' => ['title'], 'disableOnNumbers' => true, ]; - $promise = $this->index->updateTypoTolerance($newTypoTolerance); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateTypoTolerance($newTypoTolerance); + $this->index->waitForTask($task['taskUid']); $typoTolerance = $this->index->getTypoTolerance(); self::assertSame($newTypoTolerance, $typoTolerance); @@ -56,8 +56,8 @@ public function testUpdateTypoTolerance(): void public function testResetTypoTolerance(): void { - $promise = $this->index->resetTypoTolerance(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetTypoTolerance(); + $this->index->waitForTask($task['taskUid']); $typoTolerance = $this->index->getTypoTolerance(); self::assertSame(self::DEFAULT_TYPO_TOLERANCE, $typoTolerance); diff --git a/tests/Settings/WordDictionaryTest.php b/tests/Settings/WordDictionaryTest.php index bb98a691..cbf446d2 100644 --- a/tests/Settings/WordDictionaryTest.php +++ b/tests/Settings/WordDictionaryTest.php @@ -31,16 +31,16 @@ public function testUpdateWordDictionary(): void 'J. R. R.', ]; - $promise = $this->index->updateDictionary($newWordDictionary); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->updateDictionary($newWordDictionary); + $this->index->waitForTask($task['taskUid']); self::assertSame($newWordDictionary, $this->index->getDictionary()); } public function testResetWordDictionary(): void { - $promise = $this->index->resetDictionary(); - $this->index->waitForTask($promise['taskUid']); + $task = $this->index->resetDictionary(); + $this->index->waitForTask($task['taskUid']); self::assertSame(self::DEFAULT_WORD_DICTIONARY, $this->index->getDictionary()); } From 605d8dd0d617a433bad507924c6e162453553c90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 14:21:19 +0300 Subject: [PATCH 19/51] Wrap tasks in `TasksResults` object with `Task` object --- src/Contracts/TasksResults.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Contracts/TasksResults.php b/src/Contracts/TasksResults.php index 97b7ac8e..6560008c 100644 --- a/src/Contracts/TasksResults.php +++ b/src/Contracts/TasksResults.php @@ -28,7 +28,7 @@ class TasksResults extends Data public function __construct(array $params) { - parent::__construct($params['results'] ?? []); + parent::__construct(isset($params['results']) ? array_map(static fn (array $data) => Task::fromArray($data), $params['results']) : []); $this->from = $params['from'] ?? 0; $this->limit = $params['limit'] ?? 0; @@ -37,7 +37,7 @@ public function __construct(array $params) } /** - * @return array + * @return array */ public function getResults(): array { From bd8fc9a246fe42e5e09cb75f1c195d3e8233a0cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 14:22:19 +0300 Subject: [PATCH 20/51] Replace task array access usage with getters Rename `$response` to `$task` in tests --- tests/Contracts/TaskTest.php | 2 +- tests/Endpoints/BatchesTest.php | 2 +- tests/Endpoints/ClientTest.php | 21 +-- tests/Endpoints/DocumentsTest.php | 160 +++++++++++--------- tests/Endpoints/FacetSearchTest.php | 2 +- tests/Endpoints/IndexTest.php | 29 ++-- tests/Endpoints/MultiSearchTest.php | 4 +- tests/Endpoints/SearchNestedFieldsTest.php | 14 +- tests/Endpoints/SearchTest.php | 104 +++++++------ tests/Endpoints/SimilarDocumentsTest.php | 2 +- tests/Endpoints/TasksTest.php | 112 ++++++-------- tests/Endpoints/TenantTokenTest.php | 6 +- tests/Settings/DisplayedAttributesTest.php | 6 +- tests/Settings/DistinctAttributeTest.php | 6 +- tests/Settings/EmbeddersTest.php | 6 +- tests/Settings/FacetSearchTest.php | 6 +- tests/Settings/FacetingAttributesTest.php | 6 +- tests/Settings/FilterableAttributesTest.php | 10 +- tests/Settings/LocalizedAttributesTest.php | 6 +- tests/Settings/NonSeparatorTokensTest.php | 4 +- tests/Settings/PaginationTest.php | 6 +- tests/Settings/PrefixSearchTest.php | 6 +- tests/Settings/ProximityPrecisionTest.php | 6 +- tests/Settings/RankingRulesTest.php | 4 +- tests/Settings/SearchCutoffMsTest.php | 6 +- tests/Settings/SearchableAttributesTest.php | 4 +- tests/Settings/SeparatorTokensTest.php | 4 +- tests/Settings/SettingsTest.php | 10 +- tests/Settings/SortableAttributesTest.php | 6 +- tests/Settings/StopWordsTest.php | 6 +- tests/Settings/SynonymsTest.php | 8 +- tests/Settings/TypoToleranceTest.php | 4 +- tests/Settings/WordDictionaryTest.php | 4 +- tests/TestCase.php | 6 +- 34 files changed, 297 insertions(+), 291 deletions(-) diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index 85ae59e7..e6e45112 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -62,7 +62,7 @@ public function testCreate(): void ), $task->getError()); // Ensure the class supports array access retrocompatibility - self::assertSame(1, $task['taskUid']); + self::assertSame(1, $task->getTaskUid()); self::assertSame('documents', $task['indexUid']); self::assertSame('failed', $task['status']); self::assertSame('index_creation', $task['type']); diff --git a/tests/Endpoints/BatchesTest.php b/tests/Endpoints/BatchesTest.php index d29eec86..828256d3 100644 --- a/tests/Endpoints/BatchesTest.php +++ b/tests/Endpoints/BatchesTest.php @@ -36,7 +36,7 @@ public function testGetAllBatchesWithIndexUidFilters(): void public function testGetAllBatchesWithTasksFilters(): void { $tasks = $this->client->getTasks(new TasksQuery())->getResults(); - $response = $this->client->getBatches((new BatchesQuery())->setUids([$tasks[0]['uid']])); + $response = $this->client->getBatches((new BatchesQuery())->setUids([$tasks[0]->getTaskUid()])); self::assertGreaterThan(0, $response->getTotal()); } diff --git a/tests/Endpoints/ClientTest.php b/tests/Endpoints/ClientTest.php index e5c8c714..f99d099f 100644 --- a/tests/Endpoints/ClientTest.php +++ b/tests/Endpoints/ClientTest.php @@ -92,10 +92,12 @@ public function testgetIndexes(): void { $booksIndex1 = $this->safeIndexName('books-1'); $booksIndex2 = $this->safeIndexName('books-2'); - $response = $this->client->createIndex($booksIndex1); - $this->client->waitForTask($response['taskUid']); - $response = $this->client->createIndex($booksIndex2); - $this->client->waitForTask($response['taskUid']); + + $task = $this->client->createIndex($booksIndex1); + $this->client->waitForTask($task->getTaskUid()); + + $task = $this->client->createIndex($booksIndex2); + $this->client->waitForTask($task->getTaskUid()); $indexes = $this->client->getIndexes(); @@ -116,9 +118,10 @@ public function testUpdateIndex(): void $indexName = $this->safeIndexName('books-1'); $this->createEmptyIndex($indexName); - $response = $this->client->updateIndex($indexName, ['primaryKey' => 'id']); - $this->client->waitForTask($response['taskUid']); - $index = $this->client->getIndex($response['indexUid']); + $task = $this->client->updateIndex($indexName, ['primaryKey' => 'id']); + $this->client->waitForTask($task->getTaskUid()); + + $index = $this->client->getIndex($task->getIndexUid()); self::assertSame('id', $index->getPrimaryKey()); self::assertSame($indexName, $index->getUid()); @@ -131,8 +134,8 @@ public function testDeleteIndex(): void $response = $this->client->getIndexes(); self::assertCount(1, $response); - $response = $this->client->deleteIndex('index'); - $this->client->waitForTask($response['taskUid']); + $task = $this->client->deleteIndex('index'); + $this->client->waitForTask($task->getTaskUid()); $this->expectException(ApiException::class); $index = $this->client->getIndex('index'); diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 4a0b83eb..780ae2f2 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -23,7 +23,7 @@ public function testAddDocuments(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); } @@ -36,7 +36,7 @@ public function testAddDocumentsInBatches(): void self::assertCount(4, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); } $response = $index->getDocuments(); @@ -54,7 +54,7 @@ public function testAddDocumentWithSpecialChars(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $task = $index->addDocuments($documents); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count($documents), $response); @@ -75,7 +75,7 @@ public function testAddDocumentsCsv(): void $task = $index->addDocumentsCsv($documentCsv); - $update = $index->waitForTask($task['taskUid']); + $update = $index->waitForTask($task->getTaskUid()); self::assertSame('succeeded', $update['status']); self::assertNotSame(0, $update['details']['receivedDocuments']); @@ -92,7 +92,7 @@ public function testAddDocumentsCsvWithCustomSeparator(): void $task = $index->addDocumentsCsv($csv, null, '|'); - $update = $index->waitForTask($task['taskUid']); + $update = $index->waitForTask($task->getTaskUid()); self::assertSame('succeeded', $update['status']); self::assertSame(6, $update['details']['receivedDocuments']); @@ -112,7 +112,7 @@ public function testAddDocumentsJson(): void $task = $index->addDocumentsJson($documentJson); - $update = $index->waitForTask($task['taskUid']); + $update = $index->waitForTask($task->getTaskUid()); self::assertSame('succeeded', $update['status']); self::assertNotSame(0, $update['details']['receivedDocuments']); @@ -131,7 +131,7 @@ public function testAddDocumentsNdJson(): void $task = $index->addDocumentsNdjson($documentNdJson); - $update = $index->waitForTask($task['taskUid']); + $update = $index->waitForTask($task->getTaskUid()); self::assertSame('succeeded', $update['status']); self::assertNotSame(0, $update['details']['receivedDocuments']); @@ -154,8 +154,8 @@ public function testCannotAddDocumentWhenJsonEncodingFails(): void public function testGetSingleDocumentWithIntegerDocumentId(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id']); @@ -166,8 +166,8 @@ public function testGetSingleDocumentWithIntegerDocumentId(): void public function testGetSingleDocumentWithFields(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id'], ['title']); @@ -179,8 +179,8 @@ public function testGetSingleDocumentWithStringDocumentId(): void { $stringDocumentId = 'myUniqueId'; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $addDocumentResponse = $index->addDocuments([['id' => $stringDocumentId]]); - $index->waitForTask($addDocumentResponse['taskUid']); + $task = $index->addDocuments([['id' => $stringDocumentId]]); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument($stringDocumentId); self::assertSame($stringDocumentId, $response['id']); @@ -189,8 +189,8 @@ public function testGetSingleDocumentWithStringDocumentId(): void public function testGetMultipleDocumentsByIds(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $documentIds = [1, 2]; $response = $index->getDocuments((new DocumentsQuery())->setIds($documentIds)); @@ -203,15 +203,16 @@ public function testGetMultipleDocumentsByIds(): void public function testReplaceDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $replacement = [ 'id' => 2, 'title' => 'The Red And The Black', ]; - $response = $index->addDocuments([$replacement]); - $index->waitForTask($response['taskUid']); + $task = $index->addDocuments([$replacement]); + $index->waitForTask($task->getTaskUid()); + $response = $index->getDocument($replacement['id']); self::assertSame($replacement['id'], $response['id']); @@ -224,15 +225,17 @@ public function testReplaceDocuments(): void public function testUpdateDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); + $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); + $replacement = [ 'id' => 456, 'title' => 'The Little Prince', ]; $task = $index->updateDocuments([$replacement]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument($replacement['id']); self::assertSame($replacement['id'], $response['id']); @@ -247,8 +250,9 @@ public function testUpdateDocuments(): void public function testUpdateDocumentsInBatches(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $documentPromise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($documentPromise['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $replacements = [ ['id' => 1, 'title' => 'Alice Outside Wonderland'], @@ -261,8 +265,8 @@ public function testUpdateDocumentsInBatches(): void $tasks = $index->updateDocumentsInBatches($replacements, 4); self::assertCount(2, $tasks); - foreach ($tasks as $task) { - $index->waitForTask($task['taskUid']); + foreach ($tasks as $enqueuedTask) { + $index->waitForTask($enqueuedTask->getTaskUid()); } foreach ($replacements as $replacement) { @@ -280,9 +284,11 @@ public function testUpdateDocumentsByFunction(): void { $http = new Client($this->host, getenv('MEILISEARCH_API_KEY')); $http->patch('/experimental-features', ['editDocumentsByFunction' => true]); + $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $documentPromise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($documentPromise['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $function = ' if doc.id % context.modulo == 0 { @@ -291,8 +297,8 @@ public function testUpdateDocumentsByFunction(): void doc.remove("comment"); doc.remove("genre"); '; - $documentPromise = $index->updateDocumentsByFunction($function, ['context' => ['modulo' => 3]]); - $index->waitForTask($documentPromise['taskUid']); + $task = $index->updateDocumentsByFunction($function, ['context' => ['modulo' => 3]]); + $index->waitForTask($task->getTaskUid()); $documents = $index->getDocuments()->getResults(); @@ -345,7 +351,7 @@ public function testAddDocumentsCsvInBatches(): void self::assertCount(2, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); } $response = $index->getDocuments(); @@ -401,7 +407,7 @@ public function testAddDocumentsNdjsonInBatches(): void self::assertCount(2, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); } $response = $index->getDocuments(); @@ -411,15 +417,18 @@ public function testAddDocumentsNdjsonInBatches(): void public function testAddWithUpdateDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); + $document = [ 'id' => 9, 'title' => '1984', ]; + $task = $index->updateDocuments([$document]); + $index->waitForTask($task->getTaskUid()); - $index->waitForTask($task['taskUid']); $response = $index->getDocument($document['id']); self::assertSame($document['id'], $response['id']); @@ -434,13 +443,15 @@ public function testAddWithUpdateDocuments(): void public function testDeleteNonExistingDocument(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $documentId = 9; + $task = $index->deleteDocument($documentId); + $index->waitForTask($task->getTaskUid()); - $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); @@ -450,13 +461,14 @@ public function testDeleteNonExistingDocument(): void public function testDeleteSingleExistingDocumentWithDocumentIdAsInteger(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); $documentId = 123; $task = $index->deleteDocument($documentId); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS) - 1, $response); @@ -466,12 +478,14 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsInteger(): void public function testDeleteSingleExistingDocumentWithDocumentIdAsString(): void { $stringDocumentId = 'myUniqueId'; + $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $addDocumentResponse = $index->addDocuments([['id' => $stringDocumentId]]); - $index->waitForTask($addDocumentResponse['taskUid']); + $task = $index->addDocuments([['id' => $stringDocumentId]]); + + $index->waitForTask($task->getTaskUid()); $task = $index->deleteDocument($stringDocumentId); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); @@ -481,12 +495,14 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsString(): void public function testDeleteMultipleDocumentsWithDocumentIdAsInteger(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); + $documentIds = [1, 2]; $task = $index->deleteDocuments($documentIds); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS) - 2, $response); @@ -503,7 +519,7 @@ public function testDeleteMultipleDocumentsWithFilter(): void $filter = ['filter' => ['id > 0']]; $task = $index->deleteDocuments($filter); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertEmpty($response); @@ -539,11 +555,12 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsString(): void ['id' => 'myUniqueId3'], ]; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $addDocumentResponse = $index->addDocuments($documents); - $index->waitForTask($addDocumentResponse['taskUid']); + + $task = $index->addDocuments($documents); + $index->waitForTask($task->getTaskUid()); $task = $index->deleteDocuments(['myUniqueId1', 'myUniqueId3']); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(1, $response); @@ -553,11 +570,13 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsString(): void public function testDeleteAllDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $response = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($response['taskUid']); + + $task = $index->addDocuments(self::DOCUMENTS); + $index->waitForTask($task->getTaskUid()); + $task = $index->deleteAllDocuments(); + $index->waitForTask($task->getTaskUid()); - $index->waitForTask($task['taskUid']); $response = $index->getDocuments(); self::assertCount(0, $response); @@ -582,10 +601,9 @@ public function testAddDocumentWithPrimaryKey(): void ], ]; $index = $this->createEmptyIndex($this->safeIndexName('movies-1')); - $response = $index->addDocuments($documents, 'unique'); - self::assertArrayHasKey('taskUid', $response); - $index->waitForTask($response['taskUid']); + $task = $index->addDocuments($documents, 'unique'); + $index->waitForTask($task->getTaskUid()); self::assertSame('unique', $index->fetchPrimaryKey()); self::assertCount(1, $index->getDocuments()); @@ -603,7 +621,7 @@ public function testUpdateDocumentWithPrimaryKey(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateDocuments($documents, 'unique'); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame('unique', $index->fetchPrimaryKey()); self::assertCount(1, $index->getDocuments()); @@ -613,7 +631,7 @@ public function testGetDocumentsWithPagination(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments((new DocumentsQuery())->setLimit(3)); @@ -625,7 +643,7 @@ public function testGetDocumentsWithFilter(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $index->updateFilterableAttributes(['genre', 'id']); $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments((new DocumentsQuery())->setFilter(['id > 100'])); @@ -681,9 +699,9 @@ public function testGetDocumentsWithVector(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $task = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->updateDocuments(self::VECTOR_MOVIES); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(new DocumentsQuery()); self::assertArrayNotHasKey('_vectors', $response->getResults()[0]); @@ -725,7 +743,7 @@ public function testUpdateDocumentsJson(): void fclose($fileJson); $task = $index->addDocumentsJson($documentJson); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $replacement = [ [ @@ -735,7 +753,7 @@ public function testUpdateDocumentsJson(): void ]; $task = $index->updateDocumentsJson(json_encode($replacement)); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument($replacement[0]['id']); @@ -756,13 +774,13 @@ public function testUpdateDocumentsCsv(): void fclose($fileCsv); $task = $index->addDocumentsCsv($documentCsv); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $replacement = 'id,title'.PHP_EOL; $replacement .= '888221515,Young folks'.PHP_EOL; $task = $index->updateDocumentsCsv($replacement); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument(888221515); @@ -781,13 +799,13 @@ public function testUpdateDocumentsCsvWithDelimiter(): void $csv = file_get_contents('./tests/datasets/songs.csv', true); $task = $index->addDocumentsCsv($csv); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $replacement = 'id|title'.PHP_EOL; $replacement .= '888221515|Young folks'.PHP_EOL; $task = $index->updateDocumentsCsv($replacement, null, '|'); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument(888221515); @@ -804,13 +822,13 @@ public function testUpdateDocumentsNdjson(): void fclose($fileNdJson); $task = $index->addDocumentsNdjson($documentNdJson); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $replacement = json_encode(['id' => 412559401, 'title' => 'WASPTHOVEN']).PHP_EOL; $replacement .= json_encode(['id' => 70764404, 'artist' => 'Ailitp']).PHP_EOL; $task = $index->updateDocumentsNdjson($replacement); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument(412559401); self::assertSame(412559401, (int) $response['id']); @@ -841,7 +859,7 @@ public function testUpdateDocumentsCsvInBatches(): void $tasks = $index->updateDocumentsCsvInBatches($replacement, 1); self::assertCount(2, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); } $response = $index->getDocument(888221515); @@ -904,7 +922,7 @@ public function testUpdateDocumentsNdjsonInBatches(): void $tasks = $index->updateDocumentsNdjsonInBatches($replacement, 1); self::assertCount(2, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); } $response = $index->getDocument(412559401); diff --git a/tests/Endpoints/FacetSearchTest.php b/tests/Endpoints/FacetSearchTest.php index a3f57cb7..8fc6f5d3 100644 --- a/tests/Endpoints/FacetSearchTest.php +++ b/tests/Endpoints/FacetSearchTest.php @@ -19,7 +19,7 @@ protected function setUp(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateDocuments(self::DOCUMENTS); $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); } public function testBasicSearchWithFilters(): void diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 7f7d7cf2..98f9c3bf 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -114,9 +114,10 @@ public function testPrimaryKeyUpdate(): void { $primaryKey = 'id'; - $response = $this->index->update(['primaryKey' => $primaryKey]); - $this->client->waitForTask($response['taskUid']); - $index = $this->client->getIndex($response['indexUid']); + $task = $this->index->update(['primaryKey' => $primaryKey]); + $this->client->waitForTask($task->getTaskUid()); + + $index = $this->client->getIndex($task->getIndexUid()); self::assertSame($primaryKey, $index->getPrimaryKey()); self::assertSame($this->indexName, $index->getUid()); @@ -168,11 +169,11 @@ public function testGetAndFetchPrimaryKey(): void public function testGetTasks(): void { $task = $this->client->createIndex('new-index', ['primaryKey' => 'objectID']); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->client->createIndex('other-index', ['primaryKey' => 'objectID']); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $tasks = $this->index->getTasks((new TasksQuery())->setIndexUids(['other-index'])); @@ -187,10 +188,10 @@ public function testWaitForTaskDefault(): void { $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($task['taskUid']); + $response = $this->index->waitForTask($task->getTaskUid()); self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $task['taskUid']); + self::assertSame($response['uid'], $task->getTaskUid()); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('duration', $response); @@ -201,10 +202,10 @@ public function testWaitForTaskDefault(): void public function testWaitForTaskWithTimeoutAndInterval(): void { $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($task['taskUid'], 100, 20); + $response = $this->index->waitForTask($task->getTaskUid(), 100, 20); self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $task['taskUid']); + self::assertSame($response['uid'], $task->getTaskUid()); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('duration', $response); @@ -216,10 +217,10 @@ public function testWaitForTaskWithTimeoutAndInterval(): void public function testWaitForTaskWithTimeout(): void { $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($task['taskUid'], 1000); + $response = $this->index->waitForTask($task->getTaskUid(), 1000); self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $task['taskUid']); + self::assertSame($response['uid'], $task->getTaskUid()); self::assertArrayHasKey('type', $response); self::assertSame('documentAdditionOrUpdate', $response['type']); self::assertArrayHasKey('duration', $response); @@ -258,7 +259,7 @@ public function testDeleteIndexes(): void public function testSwapIndexes(): void { $task = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']]); - $response = $this->client->waitForTask($task['taskUid']); + $response = $this->client->waitForTask($task->getTaskUid()); self::assertSame(['indexA', 'indexB'], $response['details']['swaps'][0]['indexes']); self::assertSame(['indexC', 'indexD'], $response['details']['swaps'][1]['indexes']); @@ -269,7 +270,7 @@ public function testSwapIndexes(): void public function testDeleteTasks(): void { $task = $this->client->deleteTasks((new DeleteTasksQuery())->setUids([1, 2])); - $response = $this->client->waitForTask($task['taskUid']); + $response = $this->client->waitForTask($task->getTaskUid()); self::assertSame('?uids=1%2C2', $response['details']['originalFilter']); self::assertIsNumeric($response['details']['matchedTasks']); diff --git a/tests/Endpoints/MultiSearchTest.php b/tests/Endpoints/MultiSearchTest.php index 2b9062e4..15ea3cbd 100644 --- a/tests/Endpoints/MultiSearchTest.php +++ b/tests/Endpoints/MultiSearchTest.php @@ -26,7 +26,7 @@ protected function setUp(): void $this->booksIndex->updateSortableAttributes(['author']); $this->booksIndex->updateFilterableAttributes(['genre']); $task = $this->booksIndex->updateDocuments(self::DOCUMENTS); - $this->booksIndex->waitForTask($task['taskUid']); + $this->booksIndex->waitForTask($task->getTaskUid()); $this->songsIndex = $this->createEmptyIndex($this->safeIndexName('songs')); $this->songsIndex->updateFilterableAttributes(['duration-float']); @@ -35,7 +35,7 @@ protected function setUp(): void fclose($fileCsv); $task = $this->songsIndex->addDocumentsCsv($documents, null, '|'); - $this->songsIndex->waitForTask($task['taskUid']); + $this->songsIndex->waitForTask($task->getTaskUid()); } public function testSearchQueryData(): void diff --git a/tests/Endpoints/SearchNestedFieldsTest.php b/tests/Endpoints/SearchNestedFieldsTest.php index 0be61df6..bc47f78f 100644 --- a/tests/Endpoints/SearchNestedFieldsTest.php +++ b/tests/Endpoints/SearchNestedFieldsTest.php @@ -16,7 +16,7 @@ protected function setUp(): void parent::setUp(); $this->index = $this->createEmptyIndex($this->safeIndexName('nestedIndex')); $task = $this->index->updateDocuments(self::NESTED_DOCUMENTS); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); } public function testBasicSearchOnNestedFields(): void @@ -67,8 +67,8 @@ public function testSearchOnNestedFieldWithOptions(): void public function testSearchOnNestedFieldWithSearchableAtributes(): void { - $response = $this->index->updateSearchableAttributes(['title', 'info.comment']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateSearchableAttributes(['title', 'info.comment']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('An awesome'); @@ -86,8 +86,8 @@ public function testSearchOnNestedFieldWithSearchableAtributes(): void public function testSearchOnNestedFieldWithSortableAtributes(): void { - $response = $this->index->updateSortableAttributes(['info.reviewNb']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateSortableAttributes(['info.reviewNb']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('An awesome'); @@ -107,11 +107,11 @@ public function testSearchOnNestedFieldWithSortableAtributes(): void public function testSearchOnNestedFieldWithSortableAtributesAndSearchableAttributes(): void { - $response = $this->index->updateSettings([ + $task = $this->index->updateSettings([ 'searchableAttributes' => ['title', 'info.comment'], 'sortableAttributes' => ['info.reviewNb'], ]); - $this->index->waitForTask($response['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('An awesome'); diff --git a/tests/Endpoints/SearchTest.php b/tests/Endpoints/SearchTest.php index 3c52a894..c00e164d 100644 --- a/tests/Endpoints/SearchTest.php +++ b/tests/Endpoints/SearchTest.php @@ -18,7 +18,7 @@ protected function setUp(): void parent::setUp(); $this->index = $this->createEmptyIndex($this->safeIndexName()); $task = $this->index->updateDocuments(self::DOCUMENTS); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); } public function testBasicSearch(): void @@ -189,8 +189,8 @@ public function testParametersWithCustomizedCropMarker(): void public function testSearchWithMatchingStrategyALL(): void { - $response = $this->index->updateSearchableAttributes(['comment']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateSearchableAttributes(['comment']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('another french book', [ 'matchingStrategy' => 'all', @@ -201,8 +201,8 @@ public function testSearchWithMatchingStrategyALL(): void public function testSearchWithMatchingStrategyLAST(): void { - $response = $this->index->updateSearchableAttributes(['comment']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateSearchableAttributes(['comment']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('french book', [ 'matchingStrategy' => 'last', @@ -259,8 +259,8 @@ public function testParametersWithCustomizedHighlightTag(): void public function testParametersArray(): void { - $response = $this->index->updateFilterableAttributes(['title']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['title']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'limit' => 5, @@ -303,8 +303,8 @@ public function testParametersArray(): void public function testParametersCanBeAStar(): void { - $response = $this->index->updateFilterableAttributes(['title']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['title']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'limit' => 5, @@ -347,8 +347,8 @@ public function testParametersCanBeAStar(): void public function testSearchWithFilterCanBeInt(): void { - $response = $this->index->updateFilterableAttributes(['id', 'genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['id', 'genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'filter' => 'id < 12', @@ -370,8 +370,8 @@ public function testSearchWithFilterCanBeInt(): void public function testBasicSearchWithFacetDistribution(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'facets' => ['genre'], @@ -396,8 +396,8 @@ public function testBasicSearchWithFacetDistribution(): void public function testBasicSearchWithFilters(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'filter' => [['genre = fantasy']], @@ -418,8 +418,8 @@ public function testBasicSearchWithFilters(): void public function testBasicSearchWithMultipleFilter(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'filter' => ['genre = fantasy', ['genre = fantasy', 'genre = fantasy']], @@ -440,8 +440,8 @@ public function testBasicSearchWithMultipleFilter(): void public function testCustomSearchWithFilterAndAttributesToRetrieve(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'filter' => [['genre = fantasy']], @@ -470,7 +470,7 @@ public function testCustomSearchWithFilterAndAttributesToRetrieve(): void public function testSearchSortWithString(): void { - $response = $this->index->updateRankingRules([ + $task = $this->index->updateRankingRules([ 'words', 'typo', 'sort', @@ -478,9 +478,10 @@ public function testSearchSortWithString(): void 'attribute', 'exactness', ]); - $this->index->waitForTask($response['taskUid']); - $response = $this->index->updateSortableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $this->index->waitForTask($task->getTaskUid()); + + $task = $this->index->updateSortableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'sort' => ['genre:asc'], @@ -501,7 +502,7 @@ public function testSearchSortWithString(): void public function testSearchSortWithInt(): void { - $response = $this->index->updateRankingRules([ + $task = $this->index->updateRankingRules([ 'words', 'typo', 'sort', @@ -509,9 +510,10 @@ public function testSearchSortWithInt(): void 'attribute', 'exactness', ]); - $this->index->waitForTask($response['taskUid']); - $response = $this->index->updateSortableAttributes(['id']); - $this->index->waitForTask($response['taskUid']); + $this->index->waitForTask($task->getTaskUid()); + + $task = $this->index->updateSortableAttributes(['id']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'sort' => ['id:asc'], @@ -532,7 +534,7 @@ public function testSearchSortWithInt(): void public function testSearchSortWithMultipleParameter(): void { - $response = $this->index->updateRankingRules([ + $task = $this->index->updateRankingRules([ 'words', 'typo', 'sort', @@ -540,9 +542,10 @@ public function testSearchSortWithMultipleParameter(): void 'attribute', 'exactness', ]); - $this->index->waitForTask($response['taskUid']); - $response = $this->index->updateSortableAttributes(['id', 'title']); - $this->index->waitForTask($response['taskUid']); + $this->index->waitForTask($task->getTaskUid()); + + $task = $this->index->updateSortableAttributes(['id', 'title']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('prince', [ 'sort' => ['id:asc', 'title:asc'], @@ -667,8 +670,8 @@ function (array $hit): bool { return 'Le Petit Prince' === $hit['title']; } public function testBasicSearchWithFacetsOption(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search( 'prince', @@ -685,10 +688,11 @@ public function testBasicSearchWithFacetsOption(): void public function testBasicSearchWithFacetsOptionAndMultipleFacets(): void { - $response = $this->index->addDocuments([['id' => 32, 'title' => 'The Witcher', 'genre' => 'adventure', 'adaptation' => 'video game']]); - $this->index->waitForTask($response['taskUid']); - $response = $this->index->updateFilterableAttributes(['genre', 'adaptation']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->addDocuments([['id' => 32, 'title' => 'The Witcher', 'genre' => 'adventure', 'adaptation' => 'video game']]); + $this->index->waitForTask($task->getTaskUid()); + + $task = $this->index->updateFilterableAttributes(['genre', 'adaptation']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search( 'witch', @@ -710,10 +714,10 @@ public function testVectorSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->updateDocuments(self::VECTOR_MOVIES); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $response = $index->search('', ['vector' => [-0.5, 0.3, 0.85], 'hybrid' => ['semanticRatio' => 1.0, 'embedder' => 'manual']]); @@ -738,8 +742,8 @@ public function testShowRankingScoreDetails(): void public function testBasicSearchWithTransformFacetsDritributionOptionToFilter(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $filterAllFacets = function (array $facets): array { $filterOneFacet = function (array $facet): array { @@ -770,8 +774,8 @@ function (int $facetValue): bool { return 1 < $facetValue; }, public function testSearchWithAttributesToSearchOn(): void { - $response = $this->index->updateSearchableAttributes(['comment', 'title']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateSearchableAttributes(['comment', 'title']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('the', ['attributesToSearchOn' => ['comment']]); @@ -799,8 +803,8 @@ public function testSearchWithRankingScoreThreshold(): void public function testBasicSearchWithTransformFacetsDritributionOptionToMap(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $facetsToUpperFunc = function (array $facets): array { $changeOneFacet = function (array $facet): array { @@ -832,8 +836,8 @@ public function testBasicSearchWithTransformFacetsDritributionOptionToMap(): voi public function testBasicSearchWithTransformFacetsDritributionOptionToOder(): void { - $response = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($response['taskUid']); + $task = $this->index->updateFilterableAttributes(['genre']); + $this->index->waitForTask($task->getTaskUid()); $facetsToUpperFunc = function (array $facets): array { $sortOneFacet = function (array $facet): array { @@ -867,7 +871,7 @@ public function testSearchAndRetrieveFacetStats(): void $this->index->updateFilterableAttributes(['info.reviewNb']); $task = $this->index->updateDocuments(self::NESTED_DOCUMENTS); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search( null, @@ -883,7 +887,7 @@ public function testSearchWithDistinctAttribute(): void $this->index->updateFilterableAttributes(['genre']); $task = $this->index->updateDocuments(self::DOCUMENTS); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search(null, [ 'distinct' => 'genre', @@ -913,7 +917,7 @@ public function testSearchWithLocales(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateDocuments(self::DOCUMENTS); $task = $this->index->updateLocalizedAttributes([['attributePatterns' => ['title', 'comment'], 'locales' => ['fra', 'eng']]]); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $response = $this->index->search('french', [ 'locales' => ['fra', 'eng'], diff --git a/tests/Endpoints/SimilarDocumentsTest.php b/tests/Endpoints/SimilarDocumentsTest.php index c5d6e40c..c2315512 100644 --- a/tests/Endpoints/SimilarDocumentsTest.php +++ b/tests/Endpoints/SimilarDocumentsTest.php @@ -23,7 +23,7 @@ protected function setUp(): void public function testBasicSearchWithSimilarDocuments(): void { $task = $this->index->updateSettings(['embedders' => ['manual' => ['source' => 'userProvided', 'dimensions' => 3]]]); - $this->client->waitForTask($task['taskUid']); + $this->client->waitForTask($task->getTaskUid()); $response = $this->index->search('room'); diff --git a/tests/Endpoints/TasksTest.php b/tests/Endpoints/TasksTest.php index 696ae787..a6df8ed3 100644 --- a/tests/Endpoints/TasksTest.php +++ b/tests/Endpoints/TasksTest.php @@ -5,7 +5,12 @@ namespace Tests\Endpoints; use Meilisearch\Contracts\CancelTasksQuery; +use Meilisearch\Contracts\Task; +use Meilisearch\Contracts\TaskDetails\DocumentAdditionOrUpdateDetails; +use Meilisearch\Contracts\TaskDetails\TaskCancelationDetails; use Meilisearch\Contracts\TasksQuery; +use Meilisearch\Contracts\TaskStatus; +use Meilisearch\Contracts\TaskType; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\ApiException; use Tests\TestCase; @@ -24,95 +29,67 @@ protected function setUp(): void public function testGetOneTaskFromWaitTask(): void { - [$task, $response] = $this->seedIndex(); - - self::assertArrayHasKey('status', $response); - self::assertSame($response['uid'], $task['taskUid']); - self::assertArrayHasKey('type', $response); - self::assertSame('documentAdditionOrUpdate', $response['type']); - self::assertArrayHasKey('indexUid', $response); - self::assertSame($this->indexName, $response['indexUid']); - self::assertArrayHasKey('enqueuedAt', $response); - self::assertArrayHasKey('startedAt', $response); - self::assertArrayHasKey('finishedAt', $response); - self::assertIsArray($response['details']); + [$task, $completedTask] = $this->seedIndex(); + + self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskType::DocumentAdditionOrUpdate, $completedTask->getType()); + self::assertSame($this->indexName, $completedTask->getIndexUid()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $completedTask->getDetails()); } public function testGetOneTaskClient(): void { - [$task] = $this->seedIndex(); + [$seedTask] = $this->seedIndex(); - $response = $this->client->getTask($task['taskUid']); - self::assertArrayHasKey('status', $response); - self::assertSame($response['uid'], $task['taskUid']); - self::assertArrayHasKey('type', $response); - self::assertSame('documentAdditionOrUpdate', $response['type']); - self::assertArrayHasKey('indexUid', $response); - self::assertSame($this->indexName, $response['indexUid']); - self::assertArrayHasKey('enqueuedAt', $response); - self::assertArrayHasKey('startedAt', $response); - self::assertArrayHasKey('finishedAt', $response); - self::assertIsArray($response['details']); + $task = $this->index->getTask($seedTask->getTaskUid()); + self::assertSame($task->getTaskUid(), $seedTask->getTaskUid()); + self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); + self::assertSame($this->indexName, $task->getIndexUid()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $task->getDetails()); } public function testGetAllTasksClient(): void { - $response = $this->client->getTasks(); - $firstIndex = $response->getResults()[0]['uid']; + $tasks = $this->client->getTasks(); + $firstIndex = $tasks->getResults()[0]->getTaskUid(); $this->seedIndex(); - $response = $this->client->getTasks(); - $newFirstIndex = $response->getResults()[0]['uid']; + $tasks = $this->client->getTasks(); + $newFirstIndex = $tasks->getResults()[0]->getTaskUid(); self::assertNotSame($firstIndex, $newFirstIndex); } public function testGetAllTasksClientWithPagination(): void { - $response = $this->client->getTasks((new TasksQuery())->setLimit(0)); + $tasks = $this->client->getTasks((new TasksQuery())->setLimit(0)); - self::assertSame([], $response->getResults()); + self::assertSame([], $tasks->getResults()); } public function getAllTasksClientWithBatchFilter(): void { [$task] = $this->seedIndex(); - $task = $this->client->getTask($task['taskUid']); + $task = $this->client->getTask($task->getTaskUid()); - $response = $this->client->getTasks((new TasksQuery()) - ->setBatchUid($task['uid']) + $tasks = $this->client->getTasks( + (new TasksQuery()) + ->setBatchUid($task->getTaskUid()) ); - self::assertGreaterThan(0, $response->getTotal()); - } - - public function testGetOneTaskIndex(): void - { - [$task] = $this->seedIndex(); - - $response = $this->index->getTask($task['taskUid']); - self::assertArrayHasKey('status', $response); - self::assertSame($response['uid'], $task['taskUid']); - self::assertArrayHasKey('type', $response); - self::assertSame('documentAdditionOrUpdate', $response['type']); - self::assertArrayHasKey('indexUid', $response); - self::assertSame($this->indexName, $response['indexUid']); - self::assertArrayHasKey('enqueuedAt', $response); - self::assertArrayHasKey('startedAt', $response); - self::assertArrayHasKey('finishedAt', $response); - self::assertIsArray($response['details']); + self::assertGreaterThan(0, $tasks->getTotal()); } public function testGetAllTasksByIndex(): void { $response = $this->index->getTasks(); - $firstIndex = $response->getResults()[0]['uid']; + $firstIndex = $response->getResults()[0]->getTaskUid(); $newIndex = $this->createEmptyIndex($this->safeIndexName('movie-1')); $newIndex->updateDocuments(self::DOCUMENTS); $response = $this->index->getTasks(); - $newFirstIndex = $response->getResults()[0]['uid']; + $newFirstIndex = $response->getResults()[0]->getTaskUid(); self::assertSame($firstIndex, $newFirstIndex); } @@ -122,14 +99,14 @@ public function testGetAllTasksByIndexWithFilter(): void $response = $this->index->getTasks((new TasksQuery()) ->setAfterEnqueuedAt(new \DateTime('yesterday'))->setStatuses(['succeeded'])->setLimit(2)); - $firstIndex = $response->getResults()[0]['uid']; - self::assertSame('succeeded', $response->getResults()[0]['status']); + $firstIndex = $response->getResults()[0]->getTaskUid(); + self::assertSame(TaskStatus::Succeeded, $response->getResults()[0]->getStatus()); $newIndex = $this->createEmptyIndex($this->safeIndexName('movie-1')); $newIndex->updateDocuments(self::DOCUMENTS); $response = $this->index->getTasks(); - $newFirstIndex = $response->getResults()[0]['uid']; + $newFirstIndex = $response->getResults()[0]->getTaskUid(); self::assertSame($firstIndex, $newFirstIndex); self::assertGreaterThan(0, $response->getTotal()); @@ -141,24 +118,24 @@ public function testCancelTasksWithFilter(): void $query = http_build_query(['afterEnqueuedAt' => $date->format(\DateTime::RFC3339)]); $task = $this->client->cancelTasks((new CancelTasksQuery())->setAfterEnqueuedAt($date)); - self::assertSame('taskCancelation', $task['type']); - $response = $this->client->waitForTask($task['taskUid']); + $cancelTask = $this->client->waitForTask($task->getTaskUid()); + self::assertSame(TaskStatus::Succeeded, $cancelTask->getStatus()); - self::assertSame('?'.$query, $response['details']['originalFilter']); - self::assertSame('taskCancelation', $response['type']); - self::assertSame('succeeded', $response['status']); + self::assertInstanceOf(TaskCancelationDetails::class, $details = $cancelTask->getDetails()); + self::assertSame('?'.$query, $details->originalFilter); } public function testGetAllTasksInReverseOrder(): void { $sampleTasks = $this->client->getTasks(new TasksQuery()); - $sampleTasksUids = array_map(fn ($task) => $task['uid'], $sampleTasks->getResults()); + + $sampleTasksUids = array_map(static fn (Task $task) => $task->getTaskUid(), $sampleTasks->getResults()); $expectedTasks = $this->client->getTasks((new TasksQuery())->setUids($sampleTasksUids)); - $expectedTasksUids = array_map(fn ($task) => $task['uid'], $expectedTasks->getResults()); + $expectedTasksUids = array_map(static fn (Task $task) => $task->getTaskUid(), $expectedTasks->getResults()); $reversedTasks = $this->client->getTasks((new TasksQuery())->setUids($sampleTasksUids)->setReverse(true)); - $reversedTasksUids = array_map(fn ($task) => $task['uid'], $reversedTasks->getResults()); + $reversedTasksUids = array_map(static fn (Task $task) => $task->getTaskUid(), $reversedTasks->getResults()); self::assertSame(array_reverse($expectedTasksUids), $reversedTasksUids); } @@ -171,11 +148,14 @@ public function testExceptionIfNoTaskIdWhenGetting(): void $this->index->getTask(99999999); } + /** + * @return array{0: Task, 1: Task} + */ private function seedIndex(): array { $task = $this->index->updateDocuments(self::DOCUMENTS); - $response = $this->client->waitForTask($task['taskUid']); + $completedTask = $this->client->waitForTask($task->getTaskUid()); - return [$task, $response]; + return [$task, $completedTask]; } } diff --git a/tests/Endpoints/TenantTokenTest.php b/tests/Endpoints/TenantTokenTest.php index c6fe0def..9a3e7f6f 100644 --- a/tests/Endpoints/TenantTokenTest.php +++ b/tests/Endpoints/TenantTokenTest.php @@ -43,7 +43,7 @@ protected function tearDown(): void public function testGenerateTenantTokenWithSearchRulesOnly(): void { $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($task['taskUid']); + $this->client->waitForTask($task->getTaskUid()); $token = $this->privateClient->generateTenantToken($this->key->getUid(), ['*']); $tokenClient = new Client($this->host, $token); @@ -56,7 +56,7 @@ public function testGenerateTenantTokenWithSearchRulesOnly(): void public function testGenerateTenantTokenWithSearchRulesAsObject(): void { $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($task['taskUid']); + $this->client->waitForTask($task->getTaskUid()); $token = $this->privateClient->generateTenantToken($this->key->getUid(), (object) ['*' => (object) []]); $tokenClient = new Client($this->host, $token); @@ -69,7 +69,7 @@ public function testGenerateTenantTokenWithSearchRulesAsObject(): void public function testGenerateTenantTokenWithFilter(): void { $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($task['taskUid']); + $this->client->waitForTask($task->getTaskUid()); $taskFromFilter = $this->client->index('tenantToken')->updateFilterableAttributes([ 'id', ]); diff --git a/tests/Settings/DisplayedAttributesTest.php b/tests/Settings/DisplayedAttributesTest.php index 31f3272e..86ca2367 100644 --- a/tests/Settings/DisplayedAttributesTest.php +++ b/tests/Settings/DisplayedAttributesTest.php @@ -27,7 +27,7 @@ public function testUpdateDisplayedAttributes(): void $task = $index->updateDisplayedAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $displayedAttributes = $index->getDisplayedAttributes(); @@ -40,11 +40,11 @@ public function testResetDisplayedAttributes(): void $newAttributes = ['title']; $task = $index->updateDisplayedAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetDisplayedAttributes(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $displayedAttributes = $index->getDisplayedAttributes(); self::assertSame(['*'], $displayedAttributes); diff --git a/tests/Settings/DistinctAttributeTest.php b/tests/Settings/DistinctAttributeTest.php index 7fcac32b..e9a675d3 100644 --- a/tests/Settings/DistinctAttributeTest.php +++ b/tests/Settings/DistinctAttributeTest.php @@ -29,7 +29,7 @@ public function testUpdateDistinctAttribute(): void $distinctAttribute = 'description'; $task = $this->index->updateDistinctAttribute($distinctAttribute); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($distinctAttribute, $this->index->getDistinctAttribute()); } @@ -39,10 +39,10 @@ public function testResetDistinctAttribute(): void $distinctAttribute = 'description'; $task = $this->index->updateDistinctAttribute($distinctAttribute); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->resetDistinctAttribute(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertNull($this->index->getDistinctAttribute()); } diff --git a/tests/Settings/EmbeddersTest.php b/tests/Settings/EmbeddersTest.php index 02097998..f4e890bb 100644 --- a/tests/Settings/EmbeddersTest.php +++ b/tests/Settings/EmbeddersTest.php @@ -33,7 +33,7 @@ public function testUpdateEmbedders(): void $newEmbedders = ['manual' => ['source' => 'userProvided', 'dimensions' => 3, 'binaryQuantized' => true]]; $task = $this->index->updateEmbedders($newEmbedders); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newEmbedders, $this->index->getEmbedders()); } @@ -42,7 +42,7 @@ public function testResetEmbedders(): void { $task = $this->index->resetEmbedders(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(self::DEFAULT_EMBEDDER, $this->index->getEmbedders()); } @@ -63,7 +63,7 @@ public function testHuggingFacePooling(): void ], ]); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $embedders = $this->index->getEmbedders(); diff --git a/tests/Settings/FacetSearchTest.php b/tests/Settings/FacetSearchTest.php index 78634f51..6bf107b7 100644 --- a/tests/Settings/FacetSearchTest.php +++ b/tests/Settings/FacetSearchTest.php @@ -22,7 +22,7 @@ public function testUpdateFacetSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateFacetSearch(false); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertFalse($index->getFacetSearch()); } @@ -32,10 +32,10 @@ public function testResetFacetSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateFacetSearch(false); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetFacetSearch(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertTrue($index->getFacetSearch()); } diff --git a/tests/Settings/FacetingAttributesTest.php b/tests/Settings/FacetingAttributesTest.php index b7e740cf..1d9d93e7 100644 --- a/tests/Settings/FacetingAttributesTest.php +++ b/tests/Settings/FacetingAttributesTest.php @@ -26,7 +26,7 @@ public function testUpdateFacetingAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateFaceting($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame([ 'maxValuesPerFacet' => 100, @@ -40,10 +40,10 @@ public function testResetFaceting(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateFaceting($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetFaceting(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame([ 'maxValuesPerFacet' => 100, diff --git a/tests/Settings/FilterableAttributesTest.php b/tests/Settings/FilterableAttributesTest.php index c31979d1..16e34a45 100644 --- a/tests/Settings/FilterableAttributesTest.php +++ b/tests/Settings/FilterableAttributesTest.php @@ -21,7 +21,7 @@ public function testUpdateFilterableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateFilterableAttributes($expectedAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } @@ -32,10 +32,10 @@ public function testResetFilterableAttributes(): void $newAttributes = ['title']; $task = $index->updateFilterableAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetFilterableAttributes(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertEmpty($index->getFilterableAttributes()); } @@ -59,7 +59,7 @@ public function testUpdateGranularFilterableAttributes(): void ]; $task = $index->updateFilterableAttributes($expectedAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } @@ -74,7 +74,7 @@ public function testUpdateGeoWithGranularFilterableAttributes(): void ], ]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame([ [ diff --git a/tests/Settings/LocalizedAttributesTest.php b/tests/Settings/LocalizedAttributesTest.php index b38966e4..bb53987d 100644 --- a/tests/Settings/LocalizedAttributesTest.php +++ b/tests/Settings/LocalizedAttributesTest.php @@ -27,7 +27,7 @@ public function testUpdateLocalizedAttributes(): void $task = $index->updateLocalizedAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $localizedAttributes = $index->getLocalizedAttributes(); @@ -40,10 +40,10 @@ public function testResetLocalizedAttributes(): void $newAttributes = [['attributePatterns' => ['doggo'], 'locales' => ['fra']]]; $task = $index->updateLocalizedAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetLocalizedAttributes(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $localizedAttributes = $index->getLocalizedAttributes(); self::assertNull($localizedAttributes); diff --git a/tests/Settings/NonSeparatorTokensTest.php b/tests/Settings/NonSeparatorTokensTest.php index 78fc12f1..a41019fe 100644 --- a/tests/Settings/NonSeparatorTokensTest.php +++ b/tests/Settings/NonSeparatorTokensTest.php @@ -35,7 +35,7 @@ public function testUpdateNonSeparatorTokens(): void ]; $task = $this->index->updateNonSeparatorTokens($newNonSeparatorTokens); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newNonSeparatorTokens, $this->index->getNonSeparatorTokens()); } @@ -43,7 +43,7 @@ public function testUpdateNonSeparatorTokens(): void public function testResetNonSeparatorTokens(): void { $task = $this->index->resetNonSeparatorTokens(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(self::DEFAULT_NON_SEPARATOR_TOKENS, $this->index->getNonSeparatorTokens()); } diff --git a/tests/Settings/PaginationTest.php b/tests/Settings/PaginationTest.php index b106de9e..6a863f82 100644 --- a/tests/Settings/PaginationTest.php +++ b/tests/Settings/PaginationTest.php @@ -32,7 +32,7 @@ public function testUpdatePagination(): void { $task = $this->index->updatePagination(['maxTotalHits' => 100]); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(['maxTotalHits' => 100], $this->index->getPagination()); } @@ -41,10 +41,10 @@ public function testResetPagination(): void { $task = $this->index->updatePagination(['maxTotalHits' => 100]); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->resetPagination(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(self::DEFAULT_PAGINATION, $this->index->getPagination()); } diff --git a/tests/Settings/PrefixSearchTest.php b/tests/Settings/PrefixSearchTest.php index babe9d76..a160c959 100644 --- a/tests/Settings/PrefixSearchTest.php +++ b/tests/Settings/PrefixSearchTest.php @@ -22,7 +22,7 @@ public function testUpdatePrefixSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updatePrefixSearch('disabled'); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame('disabled', $index->getPrefixSearch()); } @@ -32,10 +32,10 @@ public function testResetPrefixSearch(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updatePrefixSearch('disabled'); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetPrefixSearch(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame('indexingTime', $index->getPrefixSearch()); } diff --git a/tests/Settings/ProximityPrecisionTest.php b/tests/Settings/ProximityPrecisionTest.php index 67a4529d..6b172c0b 100644 --- a/tests/Settings/ProximityPrecisionTest.php +++ b/tests/Settings/ProximityPrecisionTest.php @@ -27,7 +27,7 @@ public function testGetDefaultProximityPrecision(): void public function testUpdateProximityPrecision(): void { $task = $this->index->updateProximityPrecision('byAttribute'); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame('byAttribute', $this->index->getProximityPrecision()); } @@ -35,10 +35,10 @@ public function testUpdateProximityPrecision(): void public function testResetProximityPrecision(): void { $task = $this->index->updateProximityPrecision('byAttribute'); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->resetProximityPrecision(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame('byWord', $this->index->getProximityPrecision()); } diff --git a/tests/Settings/RankingRulesTest.php b/tests/Settings/RankingRulesTest.php index b5ad816e..e18be54a 100644 --- a/tests/Settings/RankingRulesTest.php +++ b/tests/Settings/RankingRulesTest.php @@ -43,7 +43,7 @@ public function testUpdateRankingRules(): void $task = $this->index->updateRankingRules($newRankingRules); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $rankingRules = $this->index->getRankingRules(); @@ -54,7 +54,7 @@ public function testResetRankingRules(): void { $task = $this->index->resetRankingRules(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $rankingRules = $this->index->getRankingRules(); self::assertSame(self::DEFAULT_RANKING_RULES, $rankingRules); diff --git a/tests/Settings/SearchCutoffMsTest.php b/tests/Settings/SearchCutoffMsTest.php index 4f8c6c00..01d087e5 100644 --- a/tests/Settings/SearchCutoffMsTest.php +++ b/tests/Settings/SearchCutoffMsTest.php @@ -27,7 +27,7 @@ public function testGetDefaultSearchCutoffMs(): void public function testUpdateSearchCutoffMs(): void { $task = $this->index->updateSearchCutoffMs(50); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(50, $this->index->getSearchCutoffMs()); } @@ -35,10 +35,10 @@ public function testUpdateSearchCutoffMs(): void public function testResetSearchCutoffMs(): void { $task = $this->index->updateSearchCutoffMs(50); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->resetSearchCutoffMs(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertNull($this->index->getSearchCutoffMs()); } diff --git a/tests/Settings/SearchableAttributesTest.php b/tests/Settings/SearchableAttributesTest.php index 7f0515fc..ac7f55cd 100644 --- a/tests/Settings/SearchableAttributesTest.php +++ b/tests/Settings/SearchableAttributesTest.php @@ -29,7 +29,7 @@ public function testUpdateSearchableAttributes(): void ]; $task = $indexA->updateSearchableAttributes($searchableAttributes); - $indexA->waitForTask($task['taskUid']); + $indexA->waitForTask($task->getTaskUid()); self::assertSame($searchableAttributes, $indexA->getSearchableAttributes()); } @@ -39,7 +39,7 @@ public function testResetSearchableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName('books-1')); $task = $index->resetSearchableAttributes(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame(['*'], $index->getSearchableAttributes()); } diff --git a/tests/Settings/SeparatorTokensTest.php b/tests/Settings/SeparatorTokensTest.php index c61c16ba..5f7b765e 100644 --- a/tests/Settings/SeparatorTokensTest.php +++ b/tests/Settings/SeparatorTokensTest.php @@ -35,7 +35,7 @@ public function testUpdateSeparatorTokens(): void ]; $task = $this->index->updateSeparatorTokens($newSeparatorTokens); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newSeparatorTokens, $this->index->getSeparatorTokens()); } @@ -43,7 +43,7 @@ public function testUpdateSeparatorTokens(): void public function testResetSeparatorTokens(): void { $task = $this->index->resetSeparatorTokens(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(self::DEFAULT_SEPARATOR_TOKENS, $this->index->getSeparatorTokens()); } diff --git a/tests/Settings/SettingsTest.php b/tests/Settings/SettingsTest.php index aa246e11..7dee217e 100644 --- a/tests/Settings/SettingsTest.php +++ b/tests/Settings/SettingsTest.php @@ -92,7 +92,7 @@ public function testUpdateSettings(): void 'facetSearch' => false, 'prefixSearch' => 'disabled', ]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $settings = $index->getSettings(); @@ -135,12 +135,12 @@ public function testUpdateSettingsWithoutOverwritingThem(): void 'stopWords' => ['the'], 'typoTolerance' => $new_typo_tolerance, ]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->updateSettings([ 'searchableAttributes' => ['title'], ]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $settings = $index->getSettings(); @@ -168,10 +168,10 @@ public function testResetSettings(): void 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], ]); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetSettings(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $settings = $index->getSettings(); diff --git a/tests/Settings/SortableAttributesTest.php b/tests/Settings/SortableAttributesTest.php index 673fa647..7d8a2ec4 100644 --- a/tests/Settings/SortableAttributesTest.php +++ b/tests/Settings/SortableAttributesTest.php @@ -21,7 +21,7 @@ public function testUpdateSortableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $task = $index->updateSortableAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertSame($newAttributes, $index->getSortableAttributes()); } @@ -32,10 +32,10 @@ public function testResetSortableAttributes(): void $newAttributes = ['title']; $task = $index->updateSortableAttributes($newAttributes); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); $task = $index->resetSortableAttributes(); - $index->waitForTask($task['taskUid']); + $index->waitForTask($task->getTaskUid()); self::assertEmpty($index->getSortableAttributes()); } diff --git a/tests/Settings/StopWordsTest.php b/tests/Settings/StopWordsTest.php index 447b3ba7..048dbe0e 100644 --- a/tests/Settings/StopWordsTest.php +++ b/tests/Settings/StopWordsTest.php @@ -29,7 +29,7 @@ public function testUpdateStopWords(): void $newStopWords = ['the']; $task = $this->index->updateStopWords($newStopWords); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newStopWords, $this->index->getStopWords()); } @@ -37,10 +37,10 @@ public function testUpdateStopWords(): void public function testResetStopWords(): void { $task = $this->index->updateStopWords(['the']); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->resetStopWords(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertEmpty($this->index->getStopWords()); } diff --git a/tests/Settings/SynonymsTest.php b/tests/Settings/SynonymsTest.php index 1c58c746..bd5f63d9 100644 --- a/tests/Settings/SynonymsTest.php +++ b/tests/Settings/SynonymsTest.php @@ -29,7 +29,7 @@ public function testUpdateSynonyms(): void ]; $task = $this->index->updateSynonyms($newSynonyms); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newSynonyms, $this->index->getSynonyms()); } @@ -39,7 +39,7 @@ public function testUpdateSynonymsWithEmptyArray(): void $newSynonyms = []; $task = $this->index->updateSynonyms($newSynonyms); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newSynonyms, $this->index->getSynonyms()); } @@ -49,10 +49,10 @@ public function testResetSynonyms(): void $task = $this->index->updateSynonyms([ 'hp' => ['harry potter'], ]); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $task = $this->index->resetSynonyms(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertEmpty($this->index->getSynonyms()); } diff --git a/tests/Settings/TypoToleranceTest.php b/tests/Settings/TypoToleranceTest.php index ef4ea308..11fefb82 100644 --- a/tests/Settings/TypoToleranceTest.php +++ b/tests/Settings/TypoToleranceTest.php @@ -48,7 +48,7 @@ public function testUpdateTypoTolerance(): void 'disableOnNumbers' => true, ]; $task = $this->index->updateTypoTolerance($newTypoTolerance); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $typoTolerance = $this->index->getTypoTolerance(); self::assertSame($newTypoTolerance, $typoTolerance); @@ -57,7 +57,7 @@ public function testUpdateTypoTolerance(): void public function testResetTypoTolerance(): void { $task = $this->index->resetTypoTolerance(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); $typoTolerance = $this->index->getTypoTolerance(); self::assertSame(self::DEFAULT_TYPO_TOLERANCE, $typoTolerance); diff --git a/tests/Settings/WordDictionaryTest.php b/tests/Settings/WordDictionaryTest.php index cbf446d2..19068742 100644 --- a/tests/Settings/WordDictionaryTest.php +++ b/tests/Settings/WordDictionaryTest.php @@ -32,7 +32,7 @@ public function testUpdateWordDictionary(): void ]; $task = $this->index->updateDictionary($newWordDictionary); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame($newWordDictionary, $this->index->getDictionary()); } @@ -40,7 +40,7 @@ public function testUpdateWordDictionary(): void public function testResetWordDictionary(): void { $task = $this->index->resetDictionary(); - $this->index->waitForTask($task['taskUid']); + $this->index->waitForTask($task->getTaskUid()); self::assertSame(self::DEFAULT_WORD_DICTIONARY, $this->index->getDictionary()); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 49ace79a..246aa745 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -133,10 +133,10 @@ public function assertEstimatedPagination(array $response): void public function createEmptyIndex($indexName, $options = []): Indexes { - $response = $this->client->createIndex($indexName, $options); - $this->client->waitForTask($response['taskUid']); + $task = $this->client->createIndex($indexName, $options); + $this->client->waitForTask($task->getTaskUid()); - return $this->client->getIndex($response['indexUid']); + return $this->client->getIndex($task->getIndexUid()); } public function safeIndexName(string $indexName = 'index'): string From 998de9b4ed5b1fda5d18bdfb9c83cd8f9e589981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 14:26:40 +0300 Subject: [PATCH 21/51] Completely replace array data usage --- tests/Endpoints/DocumentsTest.php | 8 ++++---- tests/Endpoints/IndexTest.php | 6 ++++-- tests/Endpoints/SearchTest.php | 5 +++-- tests/Endpoints/TenantTokenTest.php | 2 +- tests/TestCase.php | 2 +- 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 780ae2f2..bf279441 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -849,8 +849,8 @@ public function testUpdateDocumentsCsvInBatches(): void $documentCsv = file_get_contents('./tests/datasets/songs.csv', true); - $addPromise = $index->addDocumentsCsv($documentCsv); - $index->waitForTask($addPromise['taskUid']); + $task = $index->addDocumentsCsv($documentCsv); + $index->waitForTask($task->getTaskUid()); $replacement = 'id,title'.PHP_EOL; $replacement .= '888221515,Young folks'.PHP_EOL; @@ -913,8 +913,8 @@ public function testUpdateDocumentsNdjsonInBatches(): void $documentNdJson = fread($fileNdJson, filesize('./tests/datasets/songs.ndjson')); fclose($fileNdJson); - $addPromise = $index->addDocumentsNdjson($documentNdJson); - $index->waitForTask($addPromise['taskUid']); + $task = $index->addDocumentsNdjson($documentNdJson); + $index->waitForTask($task->getTaskUid()); $replacement = json_encode(['id' => 412559401, 'title' => 'WASPTHOVEN']).PHP_EOL; $replacement .= json_encode(['id' => 70764404, 'artist' => 'Ailitp']).PHP_EOL; diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 98f9c3bf..8c2b0bd0 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -231,9 +231,11 @@ public function testWaitForTaskWithTimeout(): void public function testExceptionWhenTaskTimeOut(): void { - $res = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); + $this->expectException(TimeOutException::class); - $this->index->waitForTask($res['taskUid'], 0, 20); + + $this->index->waitForTask($task->getTaskUid(), 0, 20); } public function testDeleteIndexes(): void diff --git a/tests/Endpoints/SearchTest.php b/tests/Endpoints/SearchTest.php index c00e164d..149b6dd5 100644 --- a/tests/Endpoints/SearchTest.php +++ b/tests/Endpoints/SearchTest.php @@ -131,8 +131,9 @@ public function testBasicSearchIfNoPrimaryKeyAndDocumentProvided(): void public function testExceptionIfNoIndexWhenSearching(): void { $index = $this->createEmptyIndex($this->safeIndexName('movie-1')); - $res = $index->delete(); - $index->waitForTask($res['taskUid']); + + $task = $index->delete(); + $index->waitForTask($task->getTaskUid()); $this->expectException(ApiException::class); diff --git a/tests/Endpoints/TenantTokenTest.php b/tests/Endpoints/TenantTokenTest.php index 9a3e7f6f..338c4aec 100644 --- a/tests/Endpoints/TenantTokenTest.php +++ b/tests/Endpoints/TenantTokenTest.php @@ -73,7 +73,7 @@ public function testGenerateTenantTokenWithFilter(): void $taskFromFilter = $this->client->index('tenantToken')->updateFilterableAttributes([ 'id', ]); - $this->client->waitForTask($taskFromFilter['taskUid']); + $this->client->waitForTask($taskFromFilter->getTaskUid()); $token = $this->privateClient->generateTenantToken($this->key->getUid(), (object) ['tenantToken' => (object) ['filter' => 'id > 10']]); $tokenClient = new Client($this->host, $token); diff --git a/tests/TestCase.php b/tests/TestCase.php index 246aa745..29d5e023 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -91,7 +91,7 @@ protected function tearDown(): void $tasks = []; foreach ($indexes as $index) { - $tasks[] = $index->delete()['taskUid']; + $tasks[] = $index->delete()->getTaskUid(); } $this->client->waitForTasks($tasks); From 2e771aaa0cad560e2e4f71fc15b69e72c3636ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 14:31:03 +0300 Subject: [PATCH 22/51] Fix bot review --- src/Contracts/Task.php | 6 ++++-- src/Contracts/TaskDetails/DocumentEditionDetails.php | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index d674dedd..1b77b8d2 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -147,7 +147,7 @@ public function isFinished(): bool * @param array{ * taskUid?: int, * uid?: int, - * indexUid: non-empty-string, + * indexUid?: non-empty-string, * status: non-empty-string, * type: non-empty-string, * enqueuedAt: non-empty-string, @@ -165,7 +165,7 @@ public static function fromArray(array $data): Task { return new self( $data['taskUid'] ?? $data['uid'], - $data['indexUid'], + $data['indexUid'] ?? null, TaskStatus::from($data['status']), $type = TaskType::from($data['type']), new \DateTimeImmutable($data['enqueuedAt']), @@ -186,6 +186,8 @@ public static function fromArray(array $data): Task TaskType::DumpCreation => null !== $data['details'] ? DumpCreationDetails::fromArray($data['details']) : null, TaskType::TaskCancelation => null !== $data['details'] ? TaskCancelationDetails::fromArray($data['details']) : null, TaskType::TaskDeletion => null !== $data['details'] ? TaskDeletionDetails::fromArray($data['details']) : null, + // It’s intentional that SnapshotCreation tasks don’t have a details object + // (no SnapshotCreationDetails exists and tests don’t exercise any details) TaskType::SnapshotCreation => null, }, null !== $data['error'] ? TaskError::fromArray($data['error']) : null, diff --git a/src/Contracts/TaskDetails/DocumentEditionDetails.php b/src/Contracts/TaskDetails/DocumentEditionDetails.php index 1f11b314..3186d43b 100644 --- a/src/Contracts/TaskDetails/DocumentEditionDetails.php +++ b/src/Contracts/TaskDetails/DocumentEditionDetails.php @@ -34,7 +34,7 @@ public static function fromArray(array $data): self return new self( $data['context'], $data['deletedDocuments'], - $data['deletedDocuments'], + $data['editedDocuments'], $data['function'], $data['originalFilter'], ); From a7aa9f347493f962dd0e2bad73a5f6a1fb72c31a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 14:50:06 +0300 Subject: [PATCH 23/51] Add assertion --- src/Endpoints/Indexes.php | 5 ++++- tests/Endpoints/IndexTest.php | 20 +++++++++----------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index 64869027..2d0af033 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -144,7 +144,10 @@ public function update(array $body): Task public function delete(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid) ?? []); + $response = $this->http->delete(self::PATH.'/'.$this->uid); + assert($response !== null); + + return Task::fromArray($response); } /** diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 8c2b0bd0..94f85700 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -6,6 +6,7 @@ use Meilisearch\Contracts\DeleteTasksQuery; use Meilisearch\Contracts\TasksQuery; +use Meilisearch\Contracts\TaskType; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\TimeOutException; use Tests\TestCase; @@ -245,17 +246,14 @@ public function testDeleteIndexes(): void $indexName2 = $this->safeIndexName('books-2'); $index = $this->createEmptyIndex($indexName2); - $res = $this->index->delete(); - self::assertSame($indexName1, $res['indexUid']); - self::assertArrayHasKey('type', $res); - self::assertSame('indexDeletion', $res['type']); - self::assertArrayHasKey('enqueuedAt', $res); - - $res = $index->delete(); - self::assertSame($indexName2, $res['indexUid']); - self::assertArrayHasKey('type', $res); - self::assertSame('indexDeletion', $res['type']); - self::assertArrayHasKey('enqueuedAt', $res); + $task = $this->index->delete(); + var_dump($task); + self::assertSame($indexName1, $task->getIndexUid()); + self::assertSame(TaskType::IndexDeletion, $task->getType()); + + $task = $index->delete(); + self::assertSame($indexName2, $task->getIndexUid()); + self::assertSame(TaskType::IndexDeletion, $task->getType()); } public function testSwapIndexes(): void From eaf2a27f32408a2babdc2461205592e58e87213f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 15:12:25 +0300 Subject: [PATCH 24/51] Fix missing coverage --- tests/Contracts/TaskTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index e6e45112..01728d5f 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -60,6 +60,13 @@ public function testCreate(): void 'invalid_request', 'https://docs.meilisearch.com/errors#index_not_found', ), $task->getError()); + self::assertSame([ + 'taskUid' => 1, + 'indexUid' => 'documents', + 'status' => 'failed', + 'type' => 'index_creation', + 'enqueuedAt' => '2025-04-09T10:28:12.236789123Z', + ], $task->getData()); // Ensure the class supports array access retrocompatibility self::assertSame(1, $task->getTaskUid()); From fbfaf1f62a26035419995b29e3691f88efeec63a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 14 May 2025 15:15:22 +0300 Subject: [PATCH 25/51] Fix phpstan errors --- src/Endpoints/Indexes.php | 2 +- tests/Endpoints/DocumentsTest.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index 2d0af033..5ba8eec8 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -145,7 +145,7 @@ public function update(array $body): Task public function delete(): Task { $response = $this->http->delete(self::PATH.'/'.$this->uid); - assert($response !== null); + \assert(null !== $response); return Task::fromArray($response); } diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index bf279441..6148865e 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -858,8 +858,8 @@ public function testUpdateDocumentsCsvInBatches(): void $tasks = $index->updateDocumentsCsvInBatches($replacement, 1); self::assertCount(2, $tasks); - foreach ($tasks as $task) { - $index->waitForTask($task->getTaskUid()); + foreach ($tasks as $enqueuedTask) { + $index->waitForTask($enqueuedTask->getTaskUid()); } $response = $index->getDocument(888221515); @@ -921,8 +921,8 @@ public function testUpdateDocumentsNdjsonInBatches(): void $tasks = $index->updateDocumentsNdjsonInBatches($replacement, 1); self::assertCount(2, $tasks); - foreach ($tasks as $task) { - $index->waitForTask($task->getTaskUid()); + foreach ($tasks as $enqueuedTask) { + $index->waitForTask($enqueuedTask->getTaskUid()); } $response = $index->getDocument(412559401); From a809c4dc517c7e27e91f6793d506f14500b32428 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Thu, 15 May 2025 07:27:53 +0300 Subject: [PATCH 26/51] Configure phpunit to display deprecations/errors/notices/warnings --- phpunit.xml.dist | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index fe2d97ac..34ed73ca 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,5 +1,18 @@ - + ./tests @@ -9,7 +22,15 @@ - + src/ From 7bed369bdcabb510e4fa7513e01d02d403539cc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Thu, 15 May 2025 07:33:41 +0300 Subject: [PATCH 27/51] Fix TaskDeletionDetails to accept `deletedTasks` --- src/Contracts/TaskDetails/TaskDeletionDetails.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Contracts/TaskDetails/TaskDeletionDetails.php b/src/Contracts/TaskDetails/TaskDeletionDetails.php index 7fabb30d..8c65c358 100644 --- a/src/Contracts/TaskDetails/TaskDeletionDetails.php +++ b/src/Contracts/TaskDetails/TaskDeletionDetails.php @@ -9,7 +9,7 @@ /** * @implements TaskDetails */ @@ -17,12 +17,12 @@ final class TaskDeletionDetails implements TaskDetails { /** * @param non-negative-int|null $matchedTasks The number of matched tasks. If the API key used for the request doesn’t have access to an index, tasks relating to that index will not be included in matchedTasks. - * @param non-negative-int|null $canceledTasks The number of tasks successfully canceled. If the task cancellation fails, this will be 0. null when the task status is enqueued or processing. - * @param string|null $originalFilter the filter used in the delete task request + * @param non-negative-int|null $deletedTasks The number of tasks successfully deleted. If the task deletion fails, this will be 0. null when the task status is enqueued or processing. + * @param string|null $originalFilter The filter used in the delete task request. */ public function __construct( public readonly ?int $matchedTasks, - public readonly ?int $canceledTasks, + public readonly ?int $deletedTasks, public readonly ?string $originalFilter, ) { } @@ -31,7 +31,7 @@ public static function fromArray(array $data): self { return new self( $data['matchedTasks'], - $data['canceledTasks'], + $data['deletedTasks'], $data['originalFilter'], ); } From 96c6c58739409514444cc58e8749a540260c781a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Thu, 15 May 2025 07:34:54 +0300 Subject: [PATCH 28/51] Fix `DocumentDeletionDetails` to not require `providedIds` (not available when deleting all documents) --- src/Contracts/TaskDetails/DocumentDeletionDetails.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Contracts/TaskDetails/DocumentDeletionDetails.php b/src/Contracts/TaskDetails/DocumentDeletionDetails.php index 11dd782c..317999fb 100644 --- a/src/Contracts/TaskDetails/DocumentDeletionDetails.php +++ b/src/Contracts/TaskDetails/DocumentDeletionDetails.php @@ -8,15 +8,15 @@ /** * @implements TaskDetails */ final class DocumentDeletionDetails implements TaskDetails { /** - * @param non-negative-int|null $providedIds Number of documents queued for deletion + * @param non-negative-int|null $providedIds Number of documents queued for deletion. * @param string|null $originalFilter The filter used to delete documents. Null if it was not specified. * @param int|null $deletedDocuments Number of documents deleted. `null` while the task status is enqueued or processing. */ @@ -30,7 +30,7 @@ public function __construct( public static function fromArray(array $data): self { return new self( - $data['providedIds'], + $data['providedIds'] ?? null, $data['originalFilter'] ?? null, $data['deletedDocuments'] ?? null, ); From db15b4b829be3143a8df7d6a3494f90aa518cb94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Thu, 15 May 2025 07:38:48 +0300 Subject: [PATCH 29/51] Remove task array access --- src/Contracts/Task.php | 76 +++++-------------- .../DocumentAdditionOrUpdateDetails.php | 2 +- tests/Contracts/TaskTest.php | 42 ---------- tests/Endpoints/DocumentsTest.php | 46 ++++++----- tests/Endpoints/IndexTest.php | 72 +++++++++--------- 5 files changed, 87 insertions(+), 151 deletions(-) diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index 1b77b8d2..1874f0c5 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -16,12 +16,11 @@ use Meilisearch\Contracts\TaskDetails\TaskCancelationDetails; use Meilisearch\Contracts\TaskDetails\TaskDeletionDetails; -final class Task implements \ArrayAccess +final class Task { /** * @param non-negative-int $taskUid * @param non-empty-string|null $indexUid - * @param array $data Raw data */ public function __construct( private readonly int $taskUid, @@ -36,7 +35,6 @@ public function __construct( private readonly ?int $batchUid = null, private readonly ?TaskDetails $details = null, private readonly ?TaskError $error = null, - private readonly array $data = [], ) { } @@ -106,38 +104,6 @@ public function getError(): ?TaskError return $this->error; } - /** - * @return array - */ - public function getData(): array - { - return $this->data; - } - - // @todo: deprecate - public function offsetExists(mixed $offset): bool - { - return \array_key_exists($offset, $this->data); - } - - // @todo: deprecate - public function offsetGet(mixed $offset): mixed - { - return $this->data[$offset] ?? null; - } - - // @todo: deprecate - public function offsetSet(mixed $offset, mixed $value): void - { - throw new \LogicException(\sprintf('Setting data on "%s::%s" is not supported.', get_debug_type($this), $offset)); - } - - // @todo: deprecate - public function offsetUnset(mixed $offset): void - { - throw new \LogicException(\sprintf('Unsetting data on "%s::%s" is not supported.', get_debug_type($this), $offset)); - } - public function isFinished(): bool { return TaskStatus::Enqueued !== $this->status && TaskStatus::Processing !== $this->status; @@ -151,47 +117,47 @@ public function isFinished(): bool * status: non-empty-string, * type: non-empty-string, * enqueuedAt: non-empty-string, - * startedAt?: non-empty-string, - * finishedAt?: non-empty-string, - * duration?: non-empty-string, + * startedAt?: non-empty-string|null, + * finishedAt?: non-empty-string|null, + * duration?: non-empty-string|null, * canceledBy?: int, * batchUid?: int, * details?: array|null, - * error?: array|null, - * data: array + * error?: array|null * } $data */ public static function fromArray(array $data): Task { + $details = $data['details'] ?? null; + return new self( $data['taskUid'] ?? $data['uid'], $data['indexUid'] ?? null, TaskStatus::from($data['status']), $type = TaskType::from($data['type']), new \DateTimeImmutable($data['enqueuedAt']), - isset($data['startedAt']) ? new \DateTimeImmutable($data['startedAt']) : null, - isset($data['finishedAt']) ? new \DateTimeImmutable($data['finishedAt']) : null, + \array_key_exists('startedAt', $data) && null !== $data['startedAt'] ? new \DateTimeImmutable($data['startedAt']) : null, + \array_key_exists('finishedAt', $data) && null !== $data['finishedAt'] ? new \DateTimeImmutable($data['finishedAt']) : null, $data['duration'] ?? null, $data['canceledBy'] ?? null, $data['batchUid'] ?? null, match ($type) { - TaskType::IndexCreation => null !== $data['details'] ? IndexCreationDetails::fromArray($data['details']) : null, - TaskType::IndexUpdate => null !== $data['details'] ? IndexUpdateDetails::fromArray($data['details']) : null, - TaskType::IndexDeletion => null !== $data['details'] ? IndexDeletionDetails::fromArray($data['details']) : null, - TaskType::IndexSwap => null !== $data['details'] ? IndexSwapDetails::fromArray($data['details']) : null, - TaskType::DocumentAdditionOrUpdate => null !== $data['details'] ? DocumentAdditionOrUpdateDetails::fromArray($data['details']) : null, - TaskType::DocumentDeletion => null !== $data['details'] ? DocumentDeletionDetails::fromArray($data['details']) : null, - TaskType::DocumentEdition => null !== $data['details'] ? DocumentEditionDetails::fromArray($data['details']) : null, - TaskType::SettingsUpdate => null !== $data['details'] ? SettingsUpdateDetails::fromArray($data['details']) : null, - TaskType::DumpCreation => null !== $data['details'] ? DumpCreationDetails::fromArray($data['details']) : null, - TaskType::TaskCancelation => null !== $data['details'] ? TaskCancelationDetails::fromArray($data['details']) : null, - TaskType::TaskDeletion => null !== $data['details'] ? TaskDeletionDetails::fromArray($data['details']) : null, + TaskType::IndexCreation => null !== $details ? IndexCreationDetails::fromArray($details) : null, + TaskType::IndexUpdate => null !== $details ? IndexUpdateDetails::fromArray($details) : null, + TaskType::IndexDeletion => null !== $details ? IndexDeletionDetails::fromArray($details) : null, + TaskType::IndexSwap => null !== $details ? IndexSwapDetails::fromArray($details) : null, + TaskType::DocumentAdditionOrUpdate => null !== $details ? DocumentAdditionOrUpdateDetails::fromArray($details) : null, + TaskType::DocumentDeletion => null !== $details ? DocumentDeletionDetails::fromArray($details) : null, + TaskType::DocumentEdition => null !== $details ? DocumentEditionDetails::fromArray($details) : null, + TaskType::SettingsUpdate => null !== $details ? SettingsUpdateDetails::fromArray($details) : null, + TaskType::DumpCreation => null !== $details ? DumpCreationDetails::fromArray($details) : null, + TaskType::TaskCancelation => null !== $details ? TaskCancelationDetails::fromArray($details) : null, + TaskType::TaskDeletion => null !== $details ? TaskDeletionDetails::fromArray($details) : null, // It’s intentional that SnapshotCreation tasks don’t have a details object // (no SnapshotCreationDetails exists and tests don’t exercise any details) TaskType::SnapshotCreation => null, }, - null !== $data['error'] ? TaskError::fromArray($data['error']) : null, - $data, + \array_key_exists('error', $data) && null !== $data['error'] ? TaskError::fromArray($data['error']) : null, ); } } diff --git a/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php b/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php index 785cf968..41d1b8e2 100644 --- a/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php +++ b/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php @@ -15,7 +15,7 @@ final class DocumentAdditionOrUpdateDetails implements TaskDetails { /** - * @param non-negative-int $receivedDocuments Number of documents received + * @param non-negative-int $receivedDocuments Number of documents received. * @param non-negative-int|null $indexedDocuments Number of documents indexed. `null` while the task status is enqueued or processing. */ public function __construct( diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index 01728d5f..4fddcb60 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -10,7 +10,6 @@ use Meilisearch\Contracts\TaskStatus; use Meilisearch\Contracts\TaskType; use PHPUnit\Framework\TestCase; -use Tests\MockTask; final class TaskTest extends TestCase { @@ -34,13 +33,6 @@ public function testCreate(): void 'invalid_request', 'https://docs.meilisearch.com/errors#index_not_found', ), - data: [ - 'taskUid' => 1, - 'indexUid' => 'documents', - 'status' => 'failed', - 'type' => 'index_creation', - 'enqueuedAt' => '2025-04-09T10:28:12.236789123Z', - ], ); self::assertSame(1, $task->getTaskUid()); @@ -60,20 +52,6 @@ public function testCreate(): void 'invalid_request', 'https://docs.meilisearch.com/errors#index_not_found', ), $task->getError()); - self::assertSame([ - 'taskUid' => 1, - 'indexUid' => 'documents', - 'status' => 'failed', - 'type' => 'index_creation', - 'enqueuedAt' => '2025-04-09T10:28:12.236789123Z', - ], $task->getData()); - - // Ensure the class supports array access retrocompatibility - self::assertSame(1, $task->getTaskUid()); - self::assertSame('documents', $task['indexUid']); - self::assertSame('failed', $task['status']); - self::assertSame('index_creation', $task['type']); - self::assertSame('2025-04-09T10:28:12.236789123Z', $task['enqueuedAt']); } public function testCreateEnqueuedTask(): void @@ -99,24 +77,4 @@ public function testCreateEnqueuedTask(): void self::assertNull($task->getDetails()); self::assertNull($task->getError()); } - - public function testArraySetThrows(): void - { - $task = MockTask::create(TaskType::IndexCreation); - - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Setting data on "Meilisearch\Contracts\Task::type" is not supported.'); - - $task['type'] = TaskType::IndexDeletion; - } - - public function testArrayUnsetThrows(): void - { - $task = MockTask::create(TaskType::IndexCreation); - - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Unsetting data on "Meilisearch\Contracts\Task::type" is not supported.'); - - unset($task['type']); - } } diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 6148865e..e55d6def 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -7,6 +7,8 @@ use Meilisearch\Contracts\DocumentsQuery; use Meilisearch\Contracts\Http; use Meilisearch\Contracts\Task; +use Meilisearch\Contracts\TaskDetails\DocumentAdditionOrUpdateDetails; +use Meilisearch\Contracts\TaskStatus; use Meilisearch\Contracts\TaskType; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\ApiException; @@ -74,11 +76,11 @@ public function testAddDocumentsCsv(): void fclose($fileCsv); $task = $index->addDocumentsCsv($documentCsv); + $completedTask = $index->waitForTask($task->getTaskUid()); - $update = $index->waitForTask($task->getTaskUid()); - - self::assertSame('succeeded', $update['status']); - self::assertNotSame(0, $update['details']['receivedDocuments']); + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertNotSame(0, $details->receivedDocuments); $response = $index->getDocuments(); self::assertCount(20, $response); @@ -91,11 +93,11 @@ public function testAddDocumentsCsvWithCustomSeparator(): void $csv = file_get_contents('./tests/datasets/songs-custom-separator.csv', true); $task = $index->addDocumentsCsv($csv, null, '|'); + $completedTask = $index->waitForTask($task->getTaskUid()); - $update = $index->waitForTask($task->getTaskUid()); - - self::assertSame('succeeded', $update['status']); - self::assertSame(6, $update['details']['receivedDocuments']); + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertSame(6, $details->receivedDocuments); $documents = $index->getDocuments()->getResults(); self::assertSame('Teenage Neon Jungle', $documents[4]['album']); @@ -111,11 +113,11 @@ public function testAddDocumentsJson(): void fclose($fileJson); $task = $index->addDocumentsJson($documentJson); + $completedTask = $index->waitForTask($task->getTaskUid()); - $update = $index->waitForTask($task->getTaskUid()); - - self::assertSame('succeeded', $update['status']); - self::assertNotSame(0, $update['details']['receivedDocuments']); + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertNotSame(0, $details->receivedDocuments); $response = $index->getDocuments(); self::assertCount(20, $response); @@ -130,11 +132,11 @@ public function testAddDocumentsNdJson(): void fclose($fileNdJson); $task = $index->addDocumentsNdjson($documentNdJson); + $completedTask = $index->waitForTask($task->getTaskUid()); - $update = $index->waitForTask($task->getTaskUid()); - - self::assertSame('succeeded', $update['status']); - self::assertNotSame(0, $update['details']['receivedDocuments']); + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertNotSame(0, $details->receivedDocuments); $response = $index->getDocuments(); self::assertCount(20, $response); @@ -154,8 +156,10 @@ public function testCannotAddDocumentWhenJsonEncodingFails(): void public function testGetSingleDocumentWithIntegerDocumentId(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); + $task = $index->addDocuments(self::DOCUMENTS); $index->waitForTask($task->getTaskUid()); + $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id']); @@ -166,8 +170,10 @@ public function testGetSingleDocumentWithIntegerDocumentId(): void public function testGetSingleDocumentWithFields(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); + $task = $index->addDocuments(self::DOCUMENTS); $index->waitForTask($task->getTaskUid()); + $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id'], ['title']); @@ -178,8 +184,10 @@ public function testGetSingleDocumentWithFields(): void public function testGetSingleDocumentWithStringDocumentId(): void { $stringDocumentId = 'myUniqueId'; + $index = $this->createEmptyIndex($this->safeIndexName('movies')); $task = $index->addDocuments([['id' => $stringDocumentId]]); + $index->waitForTask($task->getTaskUid()); $response = $index->getDocument($stringDocumentId); @@ -189,8 +197,10 @@ public function testGetSingleDocumentWithStringDocumentId(): void public function testGetMultipleDocumentsByIds(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); + $task = $index->addDocuments(self::DOCUMENTS); $index->waitForTask($task->getTaskUid()); + $documentIds = [1, 2]; $response = $index->getDocuments((new DocumentsQuery())->setIds($documentIds)); @@ -203,8 +213,10 @@ public function testGetMultipleDocumentsByIds(): void public function testReplaceDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); + $task = $index->addDocuments(self::DOCUMENTS); $index->waitForTask($task->getTaskUid()); + $replacement = [ 'id' => 2, 'title' => 'The Red And The Black', @@ -934,7 +946,7 @@ public function testUpdateDocumentsNdjsonInBatches(): void self::assertSame('Ailitp', $response['artist']); } - private function findDocumentWithId($documents, $documentId) + private function findDocumentWithId($documents, $documentId): ?array { foreach ($documents as $document) { if ($document['id'] === $documentId) { diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 94f85700..0fbfea06 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -5,7 +5,11 @@ namespace Tests\Endpoints; use Meilisearch\Contracts\DeleteTasksQuery; +use Meilisearch\Contracts\Task; +use Meilisearch\Contracts\TaskDetails\IndexSwapDetails; +use Meilisearch\Contracts\TaskDetails\TaskDeletionDetails; use Meilisearch\Contracts\TasksQuery; +use Meilisearch\Contracts\TaskStatus; use Meilisearch\Contracts\TaskType; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\TimeOutException; @@ -178,7 +182,7 @@ public function testGetTasks(): void $tasks = $this->index->getTasks((new TasksQuery())->setIndexUids(['other-index'])); - $allIndexUids = array_map(function ($val) { return $val['indexUid']; }, $tasks->getResults()); + $allIndexUids = array_map(static fn (Task $t) => $t->getIndexUid(), $tasks->getResults()); $results = array_unique($allIndexUids); $expected = [$this->index->getUid(), 'other-index']; @@ -188,46 +192,40 @@ public function testGetTasks(): void public function testWaitForTaskDefault(): void { $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - - $response = $this->index->waitForTask($task->getTaskUid()); - - self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $task->getTaskUid()); - self::assertArrayHasKey('type', $response); - self::assertSame('documentAdditionOrUpdate', $response['type']); - self::assertArrayHasKey('duration', $response); - self::assertArrayHasKey('startedAt', $response); - self::assertArrayHasKey('finishedAt', $response); + $completedTask = $this->index->waitForTask($task->getTaskUid()); + + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); + self::assertNotNull($completedTask->getDuration()); + self::assertNotNull($completedTask->getStartedAt()); + self::assertNotNull($completedTask->getFinishedAt()); } public function testWaitForTaskWithTimeoutAndInterval(): void { $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($task->getTaskUid(), 100, 20); - - self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $task->getTaskUid()); - self::assertArrayHasKey('type', $response); - self::assertSame('documentAdditionOrUpdate', $response['type']); - self::assertArrayHasKey('duration', $response); - self::assertArrayHasKey('enqueuedAt', $response); - self::assertArrayHasKey('startedAt', $response); - self::assertArrayHasKey('finishedAt', $response); + $completedTask = $this->index->waitForTask($task->getTaskUid(), 100, 20); + + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); + self::assertNotNull($completedTask->getDuration()); + self::assertNotNull($completedTask->getStartedAt()); + self::assertNotNull($completedTask->getFinishedAt()); } public function testWaitForTaskWithTimeout(): void { $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $response = $this->index->waitForTask($task->getTaskUid(), 1000); - - self::assertSame('succeeded', $response['status']); - self::assertSame($response['uid'], $task->getTaskUid()); - self::assertArrayHasKey('type', $response); - self::assertSame('documentAdditionOrUpdate', $response['type']); - self::assertArrayHasKey('duration', $response); - self::assertArrayHasKey('enqueuedAt', $response); - self::assertArrayHasKey('startedAt', $response); - self::assertArrayHasKey('finishedAt', $response); + $completedTask = $this->index->waitForTask($task->getTaskUid(), 1000); + + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); + self::assertNotNull($completedTask->getDuration()); + self::assertNotNull($completedTask->getStartedAt()); + self::assertNotNull($completedTask->getFinishedAt()); } public function testExceptionWhenTaskTimeOut(): void @@ -247,7 +245,6 @@ public function testDeleteIndexes(): void $index = $this->createEmptyIndex($indexName2); $task = $this->index->delete(); - var_dump($task); self::assertSame($indexName1, $task->getIndexUid()); self::assertSame(TaskType::IndexDeletion, $task->getType()); @@ -259,21 +256,24 @@ public function testDeleteIndexes(): void public function testSwapIndexes(): void { $task = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']]); - $response = $this->client->waitForTask($task->getTaskUid()); + $completedTask = $this->client->waitForTask($task->getTaskUid()); self::assertSame(['indexA', 'indexB'], $response['details']['swaps'][0]['indexes']); self::assertSame(['indexC', 'indexD'], $response['details']['swaps'][1]['indexes']); self::assertFalse($response['details']['swaps'][0]['rename']); self::assertFalse($response['details']['swaps'][1]['rename']); +// self::assertInstanceOf(IndexSwapDetails::class, $details = $completedTask->getDetails()); +// self::assertSame([['indexes' => ['indexA', 'indexB']], ['indexes' => ['indexC', 'indexD']]], $details->swaps); } public function testDeleteTasks(): void { $task = $this->client->deleteTasks((new DeleteTasksQuery())->setUids([1, 2])); - $response = $this->client->waitForTask($task->getTaskUid()); + $completedTask = $this->client->waitForTask($task->getTaskUid()); - self::assertSame('?uids=1%2C2', $response['details']['originalFilter']); - self::assertIsNumeric($response['details']['matchedTasks']); + self::assertInstanceOf(TaskDeletionDetails::class, $details = $completedTask->getDetails()); + self::assertSame('?uids=1%2C2', $details->originalFilter); + self::assertSame(0, $details->matchedTasks); } public function testParseDate(): void From c42a611e481120e32e438fd227d60aa35493fb0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Thu, 15 May 2025 07:41:44 +0300 Subject: [PATCH 30/51] Fix test --- src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php | 2 +- src/Contracts/TaskDetails/DocumentDeletionDetails.php | 2 +- src/Contracts/TaskDetails/TaskDeletionDetails.php | 2 +- tests/Endpoints/IndexTest.php | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php b/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php index 41d1b8e2..0637c850 100644 --- a/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php +++ b/src/Contracts/TaskDetails/DocumentAdditionOrUpdateDetails.php @@ -15,7 +15,7 @@ final class DocumentAdditionOrUpdateDetails implements TaskDetails { /** - * @param non-negative-int $receivedDocuments Number of documents received. + * @param non-negative-int $receivedDocuments number of documents received * @param non-negative-int|null $indexedDocuments Number of documents indexed. `null` while the task status is enqueued or processing. */ public function __construct( diff --git a/src/Contracts/TaskDetails/DocumentDeletionDetails.php b/src/Contracts/TaskDetails/DocumentDeletionDetails.php index 317999fb..74ac8d55 100644 --- a/src/Contracts/TaskDetails/DocumentDeletionDetails.php +++ b/src/Contracts/TaskDetails/DocumentDeletionDetails.php @@ -16,7 +16,7 @@ final class DocumentDeletionDetails implements TaskDetails { /** - * @param non-negative-int|null $providedIds Number of documents queued for deletion. + * @param non-negative-int|null $providedIds number of documents queued for deletion * @param string|null $originalFilter The filter used to delete documents. Null if it was not specified. * @param int|null $deletedDocuments Number of documents deleted. `null` while the task status is enqueued or processing. */ diff --git a/src/Contracts/TaskDetails/TaskDeletionDetails.php b/src/Contracts/TaskDetails/TaskDeletionDetails.php index 8c65c358..70397e36 100644 --- a/src/Contracts/TaskDetails/TaskDeletionDetails.php +++ b/src/Contracts/TaskDetails/TaskDeletionDetails.php @@ -18,7 +18,7 @@ final class TaskDeletionDetails implements TaskDetails /** * @param non-negative-int|null $matchedTasks The number of matched tasks. If the API key used for the request doesn’t have access to an index, tasks relating to that index will not be included in matchedTasks. * @param non-negative-int|null $deletedTasks The number of tasks successfully deleted. If the task deletion fails, this will be 0. null when the task status is enqueued or processing. - * @param string|null $originalFilter The filter used in the delete task request. + * @param string|null $originalFilter the filter used in the delete task request */ public function __construct( public readonly ?int $matchedTasks, diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 0fbfea06..0bdf2197 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -273,7 +273,6 @@ public function testDeleteTasks(): void self::assertInstanceOf(TaskDeletionDetails::class, $details = $completedTask->getDetails()); self::assertSame('?uids=1%2C2', $details->originalFilter); - self::assertSame(0, $details->matchedTasks); } public function testParseDate(): void From c4f33558e53c5a7af7cce471c40bbc7e13ee8148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Fri, 16 May 2025 07:28:22 +0300 Subject: [PATCH 31/51] Add missing typehints --- src/Contracts/Task.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index 1874f0c5..6c05b64d 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -21,6 +21,7 @@ final class Task /** * @param non-negative-int $taskUid * @param non-empty-string|null $indexUid + * @param non-empty-string|null $duration */ public function __construct( private readonly int $taskUid, @@ -79,6 +80,9 @@ public function getFinishedAt(): ?\DateTimeImmutable return $this->finishedAt; } + /** + * @return non-empty-string|null + */ public function getDuration(): ?string { return $this->duration; From 1412f52ffb7f17caa8273d8126b86bfc89ce1024 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Tue, 3 Jun 2025 13:39:00 +0300 Subject: [PATCH 32/51] Add the `disableOnNumbers` field to SettingsUpdateDetails on `typoTolerance` --- src/Contracts/TaskDetails/SettingsUpdateDetails.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Contracts/TaskDetails/SettingsUpdateDetails.php b/src/Contracts/TaskDetails/SettingsUpdateDetails.php index af848dd0..90c5e18c 100644 --- a/src/Contracts/TaskDetails/SettingsUpdateDetails.php +++ b/src/Contracts/TaskDetails/SettingsUpdateDetails.php @@ -47,7 +47,8 @@ * enabled: bool, * minWordSizeForTypos: array{oneTypo: int, twoTypos: int}, * disableOnWords: list, - * disableOnAttributes: list + * disableOnAttributes: list, + * disableOnNumbers: bool * } * }> */ @@ -91,7 +92,8 @@ final class SettingsUpdateDetails implements TaskDetails * enabled: bool, * minWordSizeForTypos: array{oneTypo: int, twoTypos: int}, * disableOnWords: list, - * disableOnAttributes: list + * disableOnAttributes: list, + * disableOnNumbers: bool * }|null $typoTolerance */ public function __construct( From 191c4221593aa6f26193c19c64d52689537492a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Tue, 3 Jun 2025 13:46:05 +0300 Subject: [PATCH 33/51] Fix code review --- tests/Contracts/TaskTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index 4fddcb60..ca0fdfa5 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -68,7 +68,7 @@ public function testCreateEnqueuedTask(): void self::assertSame('documents', $task->getIndexUid()); self::assertSame(TaskStatus::Enqueued, $task->getStatus()); self::assertSame(TaskType::IndexCreation, $task->getType()); - self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.236789+0000'), $task->getEnqueuedAt()); + self::assertEquals(new \DateTimeImmutable('2025-04-09T10:28:12.236789+0000'), $task->getEnqueuedAt()); self::assertNull($task->getStartedAt()); self::assertNull($task->getFinishedAt()); self::assertNull($task->getDuration()); From 4a32e0970218d1854b59c5f1b5495dba42ff8b1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Tue, 3 Jun 2025 15:43:15 +0300 Subject: [PATCH 34/51] Add `wait` method to task --- composer.json | 5 +- src/Contracts/Task.php | 26 ++- src/Endpoints/Delegates/HandlesDocuments.php | 29 +-- src/Endpoints/Delegates/HandlesSettings.php | 83 +++++---- src/Endpoints/Delegates/HandlesTasks.php | 19 -- src/Endpoints/Dumps.php | 4 +- src/Endpoints/Indexes.php | 16 +- src/Endpoints/Snapshots.php | 4 +- src/Endpoints/Tasks.php | 32 ++-- src/Exceptions/LogicException.php | 9 + src/functions.php | 15 ++ tests/Contracts/TaskTest.php | 35 ++++ tests/Endpoints/ClientTest.php | 16 +- tests/Endpoints/DocumentsTest.php | 181 +++++++------------ tests/Endpoints/FacetSearchTest.php | 3 +- tests/Endpoints/IndexTest.php | 63 +++---- tests/Endpoints/MultiSearchTest.php | 7 +- tests/Endpoints/SearchNestedFieldsTest.php | 21 +-- tests/Endpoints/SearchTest.php | 101 ++++------- tests/Endpoints/SimilarDocumentsTest.php | 3 +- tests/Endpoints/TasksTest.php | 11 +- tests/Endpoints/TenantTokenTest.php | 14 +- tests/MockTask.php | 3 +- tests/Settings/DisplayedAttributesTest.php | 12 +- tests/Settings/DistinctAttributeTest.php | 11 +- tests/Settings/EmbeddersTest.php | 15 +- tests/Settings/FacetSearchTest.php | 10 +- tests/Settings/FacetingAttributesTest.php | 10 +- tests/Settings/FilterableAttributesTest.php | 19 +- tests/Settings/LocalizedAttributesTest.php | 11 +- tests/Settings/NonSeparatorTokensTest.php | 7 +- tests/Settings/PaginationTest.php | 13 +- tests/Settings/PrefixSearchTest.php | 11 +- tests/Settings/ProximityPrecisionTest.php | 11 +- tests/Settings/RankingRulesTest.php | 8 +- tests/Settings/SearchCutoffMsTest.php | 11 +- tests/Settings/SearchableAttributesTest.php | 6 +- tests/Settings/SeparatorTokensTest.php | 7 +- tests/Settings/SettingsTest.php | 23 +-- tests/Settings/SortableAttributesTest.php | 10 +- tests/Settings/StopWordsTest.php | 11 +- tests/Settings/SynonymsTest.php | 15 +- tests/Settings/TypoToleranceTest.php | 6 +- tests/Settings/WordDictionaryTest.php | 6 +- tests/TestCase.php | 8 +- 45 files changed, 405 insertions(+), 536 deletions(-) create mode 100644 src/Exceptions/LogicException.php create mode 100644 src/functions.php diff --git a/composer.json b/composer.json index aafe621a..ef761c98 100644 --- a/composer.json +++ b/composer.json @@ -41,7 +41,10 @@ "psr-4": { "MeiliSearch\\": "src/", "Meilisearch\\": "src/" - } + }, + "files": [ + "src/functions.php" + ] }, "autoload-dev": { "psr-4": { diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index 6c05b64d..f69babdd 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -15,13 +15,15 @@ use Meilisearch\Contracts\TaskDetails\SettingsUpdateDetails; use Meilisearch\Contracts\TaskDetails\TaskCancelationDetails; use Meilisearch\Contracts\TaskDetails\TaskDeletionDetails; +use Meilisearch\Exceptions\LogicException; final class Task { /** - * @param non-negative-int $taskUid - * @param non-empty-string|null $indexUid - * @param non-empty-string|null $duration + * @param non-negative-int $taskUid + * @param non-empty-string|null $indexUid + * @param non-empty-string|null $duration + * @param \Closure(int, int, int): Task|null $await */ public function __construct( private readonly int $taskUid, @@ -36,6 +38,7 @@ public function __construct( private readonly ?int $batchUid = null, private readonly ?TaskDetails $details = null, private readonly ?TaskError $error = null, + private readonly ?\Closure $await = null, ) { } @@ -113,6 +116,19 @@ public function isFinished(): bool return TaskStatus::Enqueued !== $this->status && TaskStatus::Processing !== $this->status; } + public function wait(int $timeoutInMs = 5000, int $intervalInMs = 50): Task + { + if ($this->isFinished()) { + return $this; + } + + if (null !== $this->await) { + return ($this->await)($this->taskUid, $timeoutInMs, $intervalInMs); + } + + throw new LogicException(\sprintf('Cannot wait for task because wait function is not provided.')); + } + /** * @param array{ * taskUid?: int, @@ -129,8 +145,9 @@ public function isFinished(): bool * details?: array|null, * error?: array|null * } $data + * @param \Closure(int, int, int): Task|null $await */ - public static function fromArray(array $data): Task + public static function fromArray(array $data, ?\Closure $await = null): Task { $details = $data['details'] ?? null; @@ -162,6 +179,7 @@ public static function fromArray(array $data): Task TaskType::SnapshotCreation => null, }, \array_key_exists('error', $data) && null !== $data['error'] ? TaskError::fromArray($data['error']) : null, + $await, ); } } diff --git a/src/Endpoints/Delegates/HandlesDocuments.php b/src/Endpoints/Delegates/HandlesDocuments.php index 34479076..f21bd1d2 100644 --- a/src/Endpoints/Delegates/HandlesDocuments.php +++ b/src/Endpoints/Delegates/HandlesDocuments.php @@ -7,9 +7,12 @@ use Meilisearch\Contracts\DocumentsQuery; use Meilisearch\Contracts\DocumentsResults; use Meilisearch\Contracts\Task; +use Meilisearch\Endpoints\Tasks; use Meilisearch\Exceptions\ApiException; use Meilisearch\Exceptions\InvalidResponseBodyException; +use function Meilisearch\partial; + trait HandlesDocuments { /** @@ -42,22 +45,22 @@ public function getDocuments(?DocumentsQuery $options = null): DocumentsResults public function addDocuments(array $documents, ?string $primaryKey = null): Task { - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey])); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey]), partial(Tasks::waitTask(...), $this->http)); } public function addDocumentsJson(string $documents, ?string $primaryKey = null): Task { - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json')); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json'), partial(Tasks::waitTask(...), $this->http)); } public function addDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): Task { - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv')); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv'), partial(Tasks::waitTask(...), $this->http)); } public function addDocumentsNdjson(string $documents, ?string $primaryKey = null): Task { - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson')); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson'), partial(Tasks::waitTask(...), $this->http)); } /** @@ -104,22 +107,22 @@ public function addDocumentsNdjsonInBatches(string $documents, ?int $batchSize = public function updateDocuments(array $documents, ?string $primaryKey = null): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey])); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey]), partial(Tasks::waitTask(...), $this->http)); } public function updateDocumentsJson(string $documents, ?string $primaryKey = null): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json')); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/json'), partial(Tasks::waitTask(...), $this->http)); } public function updateDocumentsCsv(string $documents, ?string $primaryKey = null, ?string $delimiter = null): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv')); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey, 'csvDelimiter' => $delimiter], 'text/csv'), partial(Tasks::waitTask(...), $this->http)); } public function updateDocumentsNdjson(string $documents, ?string $primaryKey = null): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson')); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/documents', $documents, ['primaryKey' => $primaryKey], 'application/x-ndjson'), partial(Tasks::waitTask(...), $this->http)); } /** @@ -176,29 +179,29 @@ public function updateDocumentsNdjsonInBatches(string $documents, ?int $batchSiz */ public function updateDocumentsByFunction(string $function, array $options = []): Task { - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/edit', array_merge(['function' => $function], $options))); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/edit', array_merge(['function' => $function], $options)), partial(Tasks::waitTask(...), $this->http)); } public function deleteAllDocuments(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/documents')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/documents'), partial(Tasks::waitTask(...), $this->http)); } public function deleteDocument(string|int $documentId): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/documents/'.$documentId)); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/documents/'.$documentId), partial(Tasks::waitTask(...), $this->http)); } public function deleteDocuments(array $options): Task { try { if (\array_key_exists('filter', $options) && $options['filter']) { - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/delete', $options)); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/delete', $options), partial(Tasks::waitTask(...), $this->http)); } // backwards compatibility: // expect to be a array to send alongside as $documents_ids. - return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/delete-batch', $options)); + return Task::fromArray($this->http->post(self::PATH.'/'.$this->uid.'/documents/delete-batch', $options), partial(Tasks::waitTask(...), $this->http)); } catch (InvalidResponseBodyException $e) { throw ApiException::rethrowWithHint($e, __FUNCTION__); } diff --git a/src/Endpoints/Delegates/HandlesSettings.php b/src/Endpoints/Delegates/HandlesSettings.php index f8d9756e..4f80b531 100644 --- a/src/Endpoints/Delegates/HandlesSettings.php +++ b/src/Endpoints/Delegates/HandlesSettings.php @@ -8,6 +8,9 @@ use Meilisearch\Contracts\Index\Synonyms; use Meilisearch\Contracts\Index\TypoTolerance; use Meilisearch\Contracts\Task; +use Meilisearch\Endpoints\Tasks; + +use function Meilisearch\partial; trait HandlesSettings { @@ -26,12 +29,12 @@ public function getRankingRules(): array */ public function updateRankingRules(array $rankingRules): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/ranking-rules', $rankingRules)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/ranking-rules', $rankingRules), partial(Tasks::waitTask(...), $this->http)); } public function resetRankingRules(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/ranking-rules')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/ranking-rules'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Distinct attribute @@ -49,12 +52,12 @@ public function getDistinctAttribute(): ?string */ public function updateDistinctAttribute(string $distinctAttribute): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/distinct-attribute', $distinctAttribute)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/distinct-attribute', $distinctAttribute), partial(Tasks::waitTask(...), $this->http)); } public function resetDistinctAttribute(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/distinct-attribute')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/distinct-attribute'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Searchable attributes @@ -72,12 +75,12 @@ public function getSearchableAttributes(): array */ public function updateSearchableAttributes(array $searchableAttributes): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/searchable-attributes', $searchableAttributes)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/searchable-attributes', $searchableAttributes), partial(Tasks::waitTask(...), $this->http)); } public function resetSearchableAttributes(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/searchable-attributes')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/searchable-attributes'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Displayed attributes @@ -95,12 +98,12 @@ public function getDisplayedAttributes(): array */ public function updateDisplayedAttributes(array $displayedAttributes): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/displayed-attributes', $displayedAttributes)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/displayed-attributes', $displayedAttributes), partial(Tasks::waitTask(...), $this->http)); } public function resetDisplayedAttributes(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/displayed-attributes')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/displayed-attributes'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Localized attributes @@ -118,12 +121,12 @@ public function getLocalizedAttributes(): ?array */ public function updateLocalizedAttributes(array $localizedAttributes): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/localized-attributes', $localizedAttributes)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/localized-attributes', $localizedAttributes), partial(Tasks::waitTask(...), $this->http)); } public function resetLocalizedAttributes(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/localized-attributes')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/localized-attributes'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Faceting @@ -142,12 +145,12 @@ public function getFaceting(): array */ public function updateFaceting(array $faceting): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/faceting', $faceting)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/faceting', $faceting), partial(Tasks::waitTask(...), $this->http)); } public function resetFaceting(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/faceting')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/faceting'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Pagination @@ -165,12 +168,12 @@ public function getPagination(): array */ public function updatePagination(array $pagination): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/pagination', $pagination)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/pagination', $pagination), partial(Tasks::waitTask(...), $this->http)); } public function resetPagination(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/pagination')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/pagination'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Stop-words @@ -188,12 +191,12 @@ public function getStopWords(): array */ public function updateStopWords(array $stopWords): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/stop-words', $stopWords)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/stop-words', $stopWords), partial(Tasks::waitTask(...), $this->http)); } public function resetStopWords(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/stop-words')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/stop-words'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Synonyms @@ -212,12 +215,12 @@ public function getSynonyms(): array */ public function updateSynonyms(array $synonyms): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/synonyms', new Synonyms($synonyms))); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/synonyms', new Synonyms($synonyms)), partial(Tasks::waitTask(...), $this->http)); } public function resetSynonyms(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/synonyms')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/synonyms'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Filterable Attributes @@ -246,12 +249,12 @@ public function getFilterableAttributes(): array */ public function updateFilterableAttributes(array $filterableAttributes): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/filterable-attributes', $filterableAttributes)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/filterable-attributes', $filterableAttributes), partial(Tasks::waitTask(...), $this->http)); } public function resetFilterableAttributes(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/filterable-attributes')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/filterable-attributes'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Sortable Attributes @@ -269,12 +272,12 @@ public function getSortableAttributes(): array */ public function updateSortableAttributes(array $sortableAttributes): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/sortable-attributes', $sortableAttributes)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/sortable-attributes', $sortableAttributes), partial(Tasks::waitTask(...), $this->http)); } public function resetSortableAttributes(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/sortable-attributes')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/sortable-attributes'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Typo Tolerance @@ -305,12 +308,12 @@ public function getTypoTolerance(): array */ public function updateTypoTolerance(array $typoTolerance): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/typo-tolerance', new TypoTolerance($typoTolerance))); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/typo-tolerance', new TypoTolerance($typoTolerance)), partial(Tasks::waitTask(...), $this->http)); } public function resetTypoTolerance(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/typo-tolerance')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/typo-tolerance'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Word dictionary @@ -328,12 +331,12 @@ public function getDictionary(): array */ public function updateDictionary(array $wordDictionary): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/dictionary', $wordDictionary)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/dictionary', $wordDictionary), partial(Tasks::waitTask(...), $this->http)); } public function resetDictionary(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/dictionary')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/dictionary'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Separator tokens @@ -348,12 +351,12 @@ public function getSeparatorTokens(): array */ public function updateSeparatorTokens(array $separatorTokens): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/separator-tokens', $separatorTokens)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/separator-tokens', $separatorTokens), partial(Tasks::waitTask(...), $this->http)); } public function resetSeparatorTokens(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/separator-tokens')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/separator-tokens'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Non-Separator tokens @@ -371,12 +374,12 @@ public function getNonSeparatorTokens(): array */ public function updateNonSeparatorTokens(array $nonSeparatorTokens): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens', $nonSeparatorTokens)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens', $nonSeparatorTokens), partial(Tasks::waitTask(...), $this->http)); } public function resetNonSeparatorTokens(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/non-separator-tokens'), partial(Tasks::waitTask(...), $this->http)); } // Settings - proximityPrecision @@ -394,12 +397,12 @@ public function getProximityPrecision(): string */ public function updateProximityPrecision(string $type): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/proximity-precision', $type)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/proximity-precision', $type), partial(Tasks::waitTask(...), $this->http)); } public function resetProximityPrecision(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/proximity-precision')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/proximity-precision'), partial(Tasks::waitTask(...), $this->http)); } // Settings - searchCutoffMs @@ -417,12 +420,12 @@ public function getSearchCutoffMs(): ?int */ public function updateSearchCutoffMs(int $value): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms', $value)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms', $value), partial(Tasks::waitTask(...), $this->http)); } public function resetSearchCutoffMs(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/search-cutoff-ms'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Embedders @@ -440,7 +443,7 @@ public function getEmbedders(): ?array */ public function updateEmbedders(array $embedders): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/embedders', $embedders)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/embedders', $embedders), partial(Tasks::waitTask(...), $this->http)); } /** @@ -448,7 +451,7 @@ public function updateEmbedders(array $embedders): Task */ public function resetEmbedders(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/embedders')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/embedders'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Facet Search @@ -466,7 +469,7 @@ public function getFacetSearch(): bool */ public function updateFacetSearch(bool $facetSearch): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/facet-search', $facetSearch)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/facet-search', $facetSearch), partial(Tasks::waitTask(...), $this->http)); } /** @@ -474,7 +477,7 @@ public function updateFacetSearch(bool $facetSearch): Task */ public function resetFacetSearch(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/facet-search')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/facet-search'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Prefix Search @@ -496,7 +499,7 @@ public function getPrefixSearch(): string */ public function updatePrefixSearch(string $prefixSearch): Task { - return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/prefix-search', $prefixSearch)); + return Task::fromArray($this->http->put(self::PATH.'/'.$this->uid.'/settings/prefix-search', $prefixSearch), partial(Tasks::waitTask(...), $this->http)); } /** @@ -504,7 +507,7 @@ public function updatePrefixSearch(string $prefixSearch): Task */ public function resetPrefixSearch(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/prefix-search')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings/prefix-search'), partial(Tasks::waitTask(...), $this->http)); } // Settings - Chat diff --git a/src/Endpoints/Delegates/HandlesTasks.php b/src/Endpoints/Delegates/HandlesTasks.php index f3e07991..56f701aa 100644 --- a/src/Endpoints/Delegates/HandlesTasks.php +++ b/src/Endpoints/Delegates/HandlesTasks.php @@ -10,7 +10,6 @@ use Meilisearch\Contracts\TasksQuery; use Meilisearch\Contracts\TasksResults; use Meilisearch\Endpoints\Tasks; -use Meilisearch\Exceptions\TimeOutException; trait HandlesTasks { @@ -39,22 +38,4 @@ public function cancelTasks(?CancelTasksQuery $options = null): Task { return $this->tasks->cancelTasks($options); } - - /** - * @throws TimeOutException - */ - public function waitForTask(int $uid, int $timeoutInMs = 5000, int $intervalInMs = 50): Task - { - return $this->tasks->waitTask($uid, $timeoutInMs, $intervalInMs); - } - - /** - * @param array $uids - * - * @throws TimeOutException - */ - public function waitForTasks(array $uids, int $timeoutInMs = 5000, int $intervalInMs = 50): array - { - return $this->tasks->waitTasks($uids, $timeoutInMs, $intervalInMs); - } } diff --git a/src/Endpoints/Dumps.php b/src/Endpoints/Dumps.php index b7d031b1..aee92e02 100644 --- a/src/Endpoints/Dumps.php +++ b/src/Endpoints/Dumps.php @@ -7,12 +7,14 @@ use Meilisearch\Contracts\Endpoint; use Meilisearch\Contracts\Task; +use function Meilisearch\partial; + class Dumps extends Endpoint { protected const PATH = '/dumps'; public function create(): Task { - return Task::fromArray($this->http->post(self::PATH)); + return Task::fromArray($this->http->post(self::PATH), partial(Tasks::waitTask(...), $this->http)); } } diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index 5ba8eec8..f934f889 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -22,6 +22,8 @@ use Meilisearch\Search\SearchResult; use Meilisearch\Search\SimilarDocumentsSearchResult; +use function Meilisearch\partial; + class Indexes extends Endpoint { use HandlesDocuments; @@ -77,7 +79,7 @@ public function create(string $uid, array $options = []): Task { $options['uid'] = $uid; - return Task::fromArray($this->http->post(self::PATH, $options)); + return Task::fromArray($this->http->post(self::PATH, $options), partial(\Closure::fromCallable([Tasks::class, 'waitTask']), $this->http)); } public function all(?IndexesQuery $options = null): IndexesResults @@ -139,7 +141,7 @@ public function fetchInfo(): self public function update(array $body): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid, $body)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid, $body), partial(Tasks::waitTask(...), $this->http)); } public function delete(): Task @@ -147,7 +149,7 @@ public function delete(): Task $response = $this->http->delete(self::PATH.'/'.$this->uid); \assert(null !== $response); - return Task::fromArray($response); + return Task::fromArray($response, partial(Tasks::waitTask(...), $this->http)); } /** @@ -155,14 +157,14 @@ public function delete(): Task */ public function swapIndexes(array $indexes): Task { - return Task::fromArray($this->http->post('/swap-indexes', $indexes)); + return Task::fromArray($this->http->post('/swap-indexes', $indexes), partial(Tasks::waitTask(...), $this->http)); } // Tasks public function getTask(int $uid): Task { - return Task::fromArray($this->http->get('/tasks/'.$uid)); + return Task::fromArray($this->http->get('/tasks/'.$uid), partial(Tasks::waitTask(...), $this->http)); } public function getTasks(?TasksQuery $options = null): TasksResults @@ -250,12 +252,12 @@ public function getSettings(): array public function updateSettings($settings): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings', $settings)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings', $settings), partial(Tasks::waitTask(...), $this->http)); } public function resetSettings(): Task { - return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings')); + return Task::fromArray($this->http->delete(self::PATH.'/'.$this->uid.'/settings'), partial(Tasks::waitTask(...), $this->http)); } /** diff --git a/src/Endpoints/Snapshots.php b/src/Endpoints/Snapshots.php index e5c407e6..96db3fb3 100644 --- a/src/Endpoints/Snapshots.php +++ b/src/Endpoints/Snapshots.php @@ -7,12 +7,14 @@ use Meilisearch\Contracts\Endpoint; use Meilisearch\Contracts\Task; +use function Meilisearch\partial; + class Snapshots extends Endpoint { protected const PATH = '/snapshots'; public function create(): Task { - return Task::fromArray($this->http->post(self::PATH)); + return Task::fromArray($this->http->post(self::PATH), partial(Tasks::waitTask(...), $this->http)); } } diff --git a/src/Endpoints/Tasks.php b/src/Endpoints/Tasks.php index 2ac9ea95..8d0814d2 100644 --- a/src/Endpoints/Tasks.php +++ b/src/Endpoints/Tasks.php @@ -7,18 +7,22 @@ use Meilisearch\Contracts\CancelTasksQuery; use Meilisearch\Contracts\DeleteTasksQuery; use Meilisearch\Contracts\Endpoint; +use Meilisearch\Contracts\Http; use Meilisearch\Contracts\Task; use Meilisearch\Exceptions\TimeOutException; +use function Meilisearch\partial; + class Tasks extends Endpoint { protected const PATH = '/tasks'; public function get(int $taskUid): Task { - return Task::fromArray($this->http->get(self::PATH.'/'.$taskUid)); + return Task::fromArray($this->http->get(self::PATH.'/'.$taskUid), partial(self::waitTask(...), $this->http)); } + // @todo: must return array public function all(array $query = []): array { return $this->http->get(self::PATH.'/', $query); @@ -28,25 +32,27 @@ public function cancelTasks(?CancelTasksQuery $options): Task { $options = $options ?? new CancelTasksQuery(); - return Task::fromArray($this->http->post('/tasks/cancel', null, $options->toArray())); + return Task::fromArray($this->http->post('/tasks/cancel', null, $options->toArray()), partial(self::waitTask(...), $this->http)); } public function deleteTasks(?DeleteTasksQuery $options): Task { $options = $options ?? new DeleteTasksQuery(); - return Task::fromArray($this->http->delete(self::PATH, $options->toArray())); + return Task::fromArray($this->http->delete(self::PATH, $options->toArray()), partial(self::waitTask(...), $this->http)); } /** + * @internal + * * @throws TimeOutException */ - public function waitTask(int $taskUid, int $timeoutInMs, int $intervalInMs): Task + public static function waitTask(Http $http, int $taskUid, int $timeoutInMs, int $intervalInMs): Task { $timeoutTemp = 0; while ($timeoutInMs > $timeoutTemp) { - $task = $this->get($taskUid); + $task = Task::fromArray($http->get(self::PATH.'/'.$taskUid), partial(self::waitTask(...), $http)); if ($task->isFinished()) { return $task; @@ -58,20 +64,4 @@ public function waitTask(int $taskUid, int $timeoutInMs, int $intervalInMs): Tas throw new TimeOutException(); } - - /** - * @param array $taskUids - * - * @throws TimeOutException - */ - public function waitTasks(array $taskUids, int $timeoutInMs, int $intervalInMs): array - { - $tasks = []; - - foreach ($taskUids as $taskUid) { - $tasks[] = $this->waitTask($taskUid, $timeoutInMs, $intervalInMs); - } - - return $tasks; - } } diff --git a/src/Exceptions/LogicException.php b/src/Exceptions/LogicException.php new file mode 100644 index 00000000..9d1fda30 --- /dev/null +++ b/src/Exceptions/LogicException.php @@ -0,0 +1,9 @@ +getDetails()); self::assertNull($task->getError()); } + + public function testWait(): void + { + $await = static function () { + return MockTask::create(TaskType::IndexCreation, status: TaskStatus::Succeeded); + }; + $task = MockTask::create(TaskType::IndexCreation, await: $await(...)); + $completedTask = $task->wait(); + + self::assertNotSame($task, $completedTask); + self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); + } + + #[TestWith([TaskStatus::Succeeded])] + #[TestWith([TaskStatus::Failed])] + #[TestWith([TaskStatus::Canceled])] + public function testWaitReturnsImmediatelyIfTaskIsAlreadyFinished(TaskStatus $status): void + { + $task = MockTask::create(TaskType::IndexCreation, status: $status); + + self::assertSame($task, $task->wait()); + } + + public function testWaitThrowsWithoutFunction(): void + { + $task = MockTask::create(TaskType::IndexCreation); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot wait for task because wait function is not provided.'); + + $task->wait(); + } } diff --git a/tests/Endpoints/ClientTest.php b/tests/Endpoints/ClientTest.php index f99d099f..b0d2ca49 100644 --- a/tests/Endpoints/ClientTest.php +++ b/tests/Endpoints/ClientTest.php @@ -88,16 +88,13 @@ public function testCreateIndexWithUidInOptions(): void self::assertSame('ObjectId', $index->getPrimaryKey()); } - public function testgetIndexes(): void + public function testGetIndexes(): void { $booksIndex1 = $this->safeIndexName('books-1'); $booksIndex2 = $this->safeIndexName('books-2'); - $task = $this->client->createIndex($booksIndex1); - $this->client->waitForTask($task->getTaskUid()); - - $task = $this->client->createIndex($booksIndex2); - $this->client->waitForTask($task->getTaskUid()); + $this->client->createIndex($booksIndex1)->wait(); + $this->client->createIndex($booksIndex2)->wait(); $indexes = $this->client->getIndexes(); @@ -118,9 +115,7 @@ public function testUpdateIndex(): void $indexName = $this->safeIndexName('books-1'); $this->createEmptyIndex($indexName); - $task = $this->client->updateIndex($indexName, ['primaryKey' => 'id']); - $this->client->waitForTask($task->getTaskUid()); - + $task = $this->client->updateIndex($indexName, ['primaryKey' => 'id'])->wait(); $index = $this->client->getIndex($task->getIndexUid()); self::assertSame('id', $index->getPrimaryKey()); @@ -134,8 +129,7 @@ public function testDeleteIndex(): void $response = $this->client->getIndexes(); self::assertCount(1, $response); - $task = $this->client->deleteIndex('index'); - $this->client->waitForTask($task->getTaskUid()); + $this->client->deleteIndex('index')->wait(); $this->expectException(ApiException::class); $index = $this->client->getIndex('index'); diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index e55d6def..4d0f50de 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -23,9 +23,8 @@ final class DocumentsTest extends TestCase public function testAddDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); + $task = $index->addDocuments(self::DOCUMENTS)->wait(); - $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); } @@ -38,7 +37,7 @@ public function testAddDocumentsInBatches(): void self::assertCount(4, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task->getTaskUid()); + $task->wait(); } $response = $index->getDocuments(); @@ -54,9 +53,7 @@ public function testAddDocumentWithSpecialChars(): void ]; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments($documents); - - $index->waitForTask($task->getTaskUid()); + $task = $index->addDocuments($documents)->wait(); $response = $index->getDocuments(); self::assertCount(\count($documents), $response); @@ -75,11 +72,10 @@ public function testAddDocumentsCsv(): void $documentCsv = fread($fileCsv, filesize('./tests/datasets/songs.csv')); fclose($fileCsv); - $task = $index->addDocumentsCsv($documentCsv); - $completedTask = $index->waitForTask($task->getTaskUid()); + $task = $index->addDocumentsCsv($documentCsv)->wait(); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $task->getDetails()); self::assertNotSame(0, $details->receivedDocuments); $response = $index->getDocuments(); @@ -92,11 +88,10 @@ public function testAddDocumentsCsvWithCustomSeparator(): void $csv = file_get_contents('./tests/datasets/songs-custom-separator.csv', true); - $task = $index->addDocumentsCsv($csv, null, '|'); - $completedTask = $index->waitForTask($task->getTaskUid()); + $task = $index->addDocumentsCsv($csv, null, '|')->wait(); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $task->getDetails()); self::assertSame(6, $details->receivedDocuments); $documents = $index->getDocuments()->getResults(); @@ -112,11 +107,10 @@ public function testAddDocumentsJson(): void $documentJson = fread($fileJson, filesize('./tests/datasets/small_movies.json')); fclose($fileJson); - $task = $index->addDocumentsJson($documentJson); - $completedTask = $index->waitForTask($task->getTaskUid()); + $task = $index->addDocumentsJson($documentJson)->wait(); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $task->getDetails()); self::assertNotSame(0, $details->receivedDocuments); $response = $index->getDocuments(); @@ -131,11 +125,10 @@ public function testAddDocumentsNdJson(): void $documentNdJson = fread($fileNdJson, filesize('./tests/datasets/songs.ndjson')); fclose($fileNdJson); - $task = $index->addDocumentsNdjson($documentNdJson); - $completedTask = $index->waitForTask($task->getTaskUid()); + $task = $index->addDocumentsNdjson($documentNdJson)->wait(); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $completedTask->getDetails()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertInstanceOf(DocumentAdditionOrUpdateDetails::class, $details = $task->getDetails()); self::assertNotSame(0, $details->receivedDocuments); $response = $index->getDocuments(); @@ -157,8 +150,7 @@ public function testGetSingleDocumentWithIntegerDocumentId(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id']); @@ -171,8 +163,7 @@ public function testGetSingleDocumentWithFields(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $doc = $this->findDocumentWithId(self::DOCUMENTS, 4); $response = $index->getDocument($doc['id'], ['title']); @@ -186,9 +177,8 @@ public function testGetSingleDocumentWithStringDocumentId(): void $stringDocumentId = 'myUniqueId'; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments([['id' => $stringDocumentId]]); + $index->addDocuments([['id' => $stringDocumentId]])->wait(); - $index->waitForTask($task->getTaskUid()); $response = $index->getDocument($stringDocumentId); self::assertSame($stringDocumentId, $response['id']); @@ -198,8 +188,7 @@ public function testGetMultipleDocumentsByIds(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $documentIds = [1, 2]; $response = $index->getDocuments((new DocumentsQuery())->setIds($documentIds)); @@ -214,16 +203,14 @@ public function testReplaceDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $task = $index->addDocuments(self::DOCUMENTS)->wait(); $replacement = [ 'id' => 2, 'title' => 'The Red And The Black', ]; - $task = $index->addDocuments([$replacement]); - $index->waitForTask($task->getTaskUid()); + $task = $index->addDocuments([$replacement])->wait(); $response = $index->getDocument($replacement['id']); @@ -238,16 +225,14 @@ public function testUpdateDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $replacement = [ 'id' => 456, 'title' => 'The Little Prince', ]; - $task = $index->updateDocuments([$replacement]); + $index->updateDocuments([$replacement])->wait(); - $index->waitForTask($task->getTaskUid()); $response = $index->getDocument($replacement['id']); self::assertSame($replacement['id'], $response['id']); @@ -263,8 +248,7 @@ public function testUpdateDocumentsInBatches(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $replacements = [ ['id' => 1, 'title' => 'Alice Outside Wonderland'], @@ -277,8 +261,8 @@ public function testUpdateDocumentsInBatches(): void $tasks = $index->updateDocumentsInBatches($replacements, 4); self::assertCount(2, $tasks); - foreach ($tasks as $enqueuedTask) { - $index->waitForTask($enqueuedTask->getTaskUid()); + foreach ($tasks as $task) { + $task->wait(); } foreach ($replacements as $replacement) { @@ -299,8 +283,7 @@ public function testUpdateDocumentsByFunction(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $task = $index->addDocuments(self::DOCUMENTS)->wait(); $function = ' if doc.id % context.modulo == 0 { @@ -309,8 +292,7 @@ public function testUpdateDocumentsByFunction(): void doc.remove("comment"); doc.remove("genre"); '; - $task = $index->updateDocumentsByFunction($function, ['context' => ['modulo' => 3]]); - $index->waitForTask($task->getTaskUid()); + $index->updateDocumentsByFunction($function, ['context' => ['modulo' => 3]])->wait(); $documents = $index->getDocuments()->getResults(); @@ -363,7 +345,7 @@ public function testAddDocumentsCsvInBatches(): void self::assertCount(2, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task->getTaskUid()); + $task->wait(); } $response = $index->getDocuments(); @@ -419,7 +401,7 @@ public function testAddDocumentsNdjsonInBatches(): void self::assertCount(2, $tasks); foreach ($tasks as $task) { - $index->waitForTask($task->getTaskUid()); + $task->wait(); } $response = $index->getDocuments(); @@ -430,16 +412,14 @@ public function testAddWithUpdateDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $task = $index->addDocuments(self::DOCUMENTS)->wait(); $document = [ 'id' => 9, 'title' => '1984', ]; - $task = $index->updateDocuments([$document]); - $index->waitForTask($task->getTaskUid()); + $task = $index->updateDocuments([$document])->wait(); $response = $index->getDocument($document['id']); @@ -456,13 +436,11 @@ public function testDeleteNonExistingDocument(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $documentId = 9; - $task = $index->deleteDocument($documentId); - $index->waitForTask($task->getTaskUid()); + $index->deleteDocument($documentId)->wait(); $response = $index->getDocuments(); @@ -474,13 +452,11 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsInteger(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $documentId = 123; - $task = $index->deleteDocument($documentId); + $index->deleteDocument($documentId)->wait(); - $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS) - 1, $response); @@ -492,12 +468,9 @@ public function testDeleteSingleExistingDocumentWithDocumentIdAsString(): void $stringDocumentId = 'myUniqueId'; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments([['id' => $stringDocumentId]]); - - $index->waitForTask($task->getTaskUid()); + $index->addDocuments([['id' => $stringDocumentId]])->wait(); - $task = $index->deleteDocument($stringDocumentId); - $index->waitForTask($task->getTaskUid()); + $index->deleteDocument($stringDocumentId)->wait(); $response = $index->getDocuments(); @@ -508,13 +481,11 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsInteger(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $documentIds = [1, 2]; - $task = $index->deleteDocuments($documentIds); + $index->deleteDocuments($documentIds)->wait(); - $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS) - 2, $response); @@ -529,9 +500,8 @@ public function testDeleteMultipleDocumentsWithFilter(): void $index->updateFilterableAttributes(['id']); $filter = ['filter' => ['id > 0']]; - $task = $index->deleteDocuments($filter); + $index->deleteDocuments($filter)->wait(); - $index->waitForTask($task->getTaskUid()); $response = $index->getDocuments(); self::assertEmpty($response); @@ -568,11 +538,9 @@ public function testDeleteMultipleDocumentsWithDocumentIdAsString(): void ]; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments($documents); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments($documents)->wait(); - $task = $index->deleteDocuments(['myUniqueId1', 'myUniqueId3']); - $index->waitForTask($task->getTaskUid()); + $index->deleteDocuments(['myUniqueId1', 'myUniqueId3'])->wait(); $response = $index->getDocuments(); self::assertCount(1, $response); @@ -583,11 +551,9 @@ public function testDeleteAllDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); - $task = $index->deleteAllDocuments(); - $index->waitForTask($task->getTaskUid()); + $index->deleteAllDocuments()->wait(); $response = $index->getDocuments(); @@ -614,8 +580,7 @@ public function testAddDocumentWithPrimaryKey(): void ]; $index = $this->createEmptyIndex($this->safeIndexName('movies-1')); - $task = $index->addDocuments($documents, 'unique'); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments($documents, 'unique')->wait(); self::assertSame('unique', $index->fetchPrimaryKey()); self::assertCount(1, $index->getDocuments()); @@ -631,9 +596,7 @@ public function testUpdateDocumentWithPrimaryKey(): void ], ]; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateDocuments($documents, 'unique'); - - $index->waitForTask($task->getTaskUid()); + $index->updateDocuments($documents, 'unique')->wait(); self::assertSame('unique', $index->fetchPrimaryKey()); self::assertCount(1, $index->getDocuments()); @@ -642,8 +605,7 @@ public function testUpdateDocumentWithPrimaryKey(): void public function testGetDocumentsWithPagination(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $response = $index->getDocuments((new DocumentsQuery())->setLimit(3)); @@ -654,8 +616,7 @@ public function testGetDocumentsWithFilter(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); $index->updateFilterableAttributes(['genre', 'id']); - $task = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($task->getTaskUid()); + $index->addDocuments(self::DOCUMENTS)->wait(); $response = $index->getDocuments((new DocumentsQuery())->setFilter(['id > 100'])); @@ -710,10 +671,8 @@ public function testGetDocumentsWithVector(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $index->waitForTask($task->getTaskUid()); - $task = $index->updateDocuments(self::VECTOR_MOVIES); - $index->waitForTask($task->getTaskUid()); + $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]])->wait(); + $index->updateDocuments(self::VECTOR_MOVIES)->wait(); $response = $index->getDocuments(new DocumentsQuery()); self::assertArrayNotHasKey('_vectors', $response->getResults()[0]); @@ -754,8 +713,7 @@ public function testUpdateDocumentsJson(): void $documentJson = fread($fileJson, filesize('./tests/datasets/small_movies.json')); fclose($fileJson); - $task = $index->addDocumentsJson($documentJson); - $index->waitForTask($task->getTaskUid()); + $index->addDocumentsJson($documentJson)->wait(); $replacement = [ [ @@ -764,8 +722,7 @@ public function testUpdateDocumentsJson(): void ], ]; - $task = $index->updateDocumentsJson(json_encode($replacement)); - $index->waitForTask($task->getTaskUid()); + $index->updateDocumentsJson(json_encode($replacement))->wait(); $response = $index->getDocument($replacement[0]['id']); @@ -785,14 +742,12 @@ public function testUpdateDocumentsCsv(): void $documentCsv = fread($fileCsv, filesize('./tests/datasets/songs.csv')); fclose($fileCsv); - $task = $index->addDocumentsCsv($documentCsv); - $index->waitForTask($task->getTaskUid()); + $index->addDocumentsCsv($documentCsv)->wait(); $replacement = 'id,title'.PHP_EOL; $replacement .= '888221515,Young folks'.PHP_EOL; - $task = $index->updateDocumentsCsv($replacement); - $index->waitForTask($task->getTaskUid()); + $index->updateDocumentsCsv($replacement)->wait(); $response = $index->getDocument(888221515); @@ -810,14 +765,12 @@ public function testUpdateDocumentsCsvWithDelimiter(): void $csv = file_get_contents('./tests/datasets/songs.csv', true); - $task = $index->addDocumentsCsv($csv); - $index->waitForTask($task->getTaskUid()); + $index->addDocumentsCsv($csv)->wait(); $replacement = 'id|title'.PHP_EOL; $replacement .= '888221515|Young folks'.PHP_EOL; - $task = $index->updateDocumentsCsv($replacement, null, '|'); - $index->waitForTask($task->getTaskUid()); + $index->updateDocumentsCsv($replacement, null, '|')->wait(); $response = $index->getDocument(888221515); @@ -833,14 +786,12 @@ public function testUpdateDocumentsNdjson(): void $documentNdJson = fread($fileNdJson, filesize('./tests/datasets/songs.ndjson')); fclose($fileNdJson); - $task = $index->addDocumentsNdjson($documentNdJson); - $index->waitForTask($task->getTaskUid()); + $index->addDocumentsNdjson($documentNdJson)->wait(); $replacement = json_encode(['id' => 412559401, 'title' => 'WASPTHOVEN']).PHP_EOL; $replacement .= json_encode(['id' => 70764404, 'artist' => 'Ailitp']).PHP_EOL; - $task = $index->updateDocumentsNdjson($replacement); - $index->waitForTask($task->getTaskUid()); + $index->updateDocumentsNdjson($replacement)->wait(); $response = $index->getDocument(412559401); self::assertSame(412559401, (int) $response['id']); @@ -861,8 +812,7 @@ public function testUpdateDocumentsCsvInBatches(): void $documentCsv = file_get_contents('./tests/datasets/songs.csv', true); - $task = $index->addDocumentsCsv($documentCsv); - $index->waitForTask($task->getTaskUid()); + $index->addDocumentsCsv($documentCsv)->wait(); $replacement = 'id,title'.PHP_EOL; $replacement .= '888221515,Young folks'.PHP_EOL; @@ -870,8 +820,8 @@ public function testUpdateDocumentsCsvInBatches(): void $tasks = $index->updateDocumentsCsvInBatches($replacement, 1); self::assertCount(2, $tasks); - foreach ($tasks as $enqueuedTask) { - $index->waitForTask($enqueuedTask->getTaskUid()); + foreach ($tasks as $task) { + $task->wait(); } $response = $index->getDocument(888221515); @@ -925,16 +875,15 @@ public function testUpdateDocumentsNdjsonInBatches(): void $documentNdJson = fread($fileNdJson, filesize('./tests/datasets/songs.ndjson')); fclose($fileNdJson); - $task = $index->addDocumentsNdjson($documentNdJson); - $index->waitForTask($task->getTaskUid()); + $index->addDocumentsNdjson($documentNdJson)->wait(); $replacement = json_encode(['id' => 412559401, 'title' => 'WASPTHOVEN']).PHP_EOL; $replacement .= json_encode(['id' => 70764404, 'artist' => 'Ailitp']).PHP_EOL; $tasks = $index->updateDocumentsNdjsonInBatches($replacement, 1); self::assertCount(2, $tasks); - foreach ($tasks as $enqueuedTask) { - $index->waitForTask($enqueuedTask->getTaskUid()); + foreach ($tasks as $task) { + $task->wait(); } $response = $index->getDocument(412559401); diff --git a/tests/Endpoints/FacetSearchTest.php b/tests/Endpoints/FacetSearchTest.php index 8fc6f5d3..a2991153 100644 --- a/tests/Endpoints/FacetSearchTest.php +++ b/tests/Endpoints/FacetSearchTest.php @@ -18,8 +18,7 @@ protected function setUp(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateDocuments(self::DOCUMENTS); - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); } public function testBasicSearchWithFilters(): void diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 0bdf2197..3e3a7946 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -119,8 +119,7 @@ public function testPrimaryKeyUpdate(): void { $primaryKey = 'id'; - $task = $this->index->update(['primaryKey' => $primaryKey]); - $this->client->waitForTask($task->getTaskUid()); + $task = $this->index->update(['primaryKey' => $primaryKey])->wait(); $index = $this->client->getIndex($task->getIndexUid()); @@ -173,12 +172,9 @@ public function testGetAndFetchPrimaryKey(): void public function testGetTasks(): void { - $task = $this->client->createIndex('new-index', ['primaryKey' => 'objectID']); - $this->index->waitForTask($task->getTaskUid()); - $task = $this->client->createIndex('other-index', ['primaryKey' => 'objectID']); - $this->index->waitForTask($task->getTaskUid()); - $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $this->index->waitForTask($task->getTaskUid()); + $this->client->createIndex('new-index', ['primaryKey' => 'objectID'])->wait(); + $this->client->createIndex('other-index', ['primaryKey' => 'objectID'])->wait(); + $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(); $tasks = $this->index->getTasks((new TasksQuery())->setIndexUids(['other-index'])); @@ -191,41 +187,38 @@ public function testGetTasks(): void public function testWaitForTaskDefault(): void { - $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $completedTask = $this->index->waitForTask($task->getTaskUid()); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertSame($task->getTaskUid(), $task->getTaskUid()); self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); - self::assertNotNull($completedTask->getDuration()); - self::assertNotNull($completedTask->getStartedAt()); - self::assertNotNull($completedTask->getFinishedAt()); + self::assertNotNull($task->getDuration()); + self::assertNotNull($task->getStartedAt()); + self::assertNotNull($task->getFinishedAt()); } public function testWaitForTaskWithTimeoutAndInterval(): void { - $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $completedTask = $this->index->waitForTask($task->getTaskUid(), 100, 20); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(750, 20); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertSame($task->getTaskUid(), $task->getTaskUid()); self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); - self::assertNotNull($completedTask->getDuration()); - self::assertNotNull($completedTask->getStartedAt()); - self::assertNotNull($completedTask->getFinishedAt()); + self::assertNotNull($task->getDuration()); + self::assertNotNull($task->getStartedAt()); + self::assertNotNull($task->getFinishedAt()); } public function testWaitForTaskWithTimeout(): void { - $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']]); - $completedTask = $this->index->waitForTask($task->getTaskUid(), 1000); + $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(1000); - self::assertSame(TaskStatus::Succeeded, $completedTask->getStatus()); - self::assertSame($completedTask->getTaskUid(), $task->getTaskUid()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertSame($task->getTaskUid(), $task->getTaskUid()); self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); - self::assertNotNull($completedTask->getDuration()); - self::assertNotNull($completedTask->getStartedAt()); - self::assertNotNull($completedTask->getFinishedAt()); + self::assertNotNull($task->getDuration()); + self::assertNotNull($task->getStartedAt()); + self::assertNotNull($task->getFinishedAt()); } public function testExceptionWhenTaskTimeOut(): void @@ -234,7 +227,7 @@ public function testExceptionWhenTaskTimeOut(): void $this->expectException(TimeOutException::class); - $this->index->waitForTask($task->getTaskUid(), 0, 20); + $task->wait(0, 20); } public function testDeleteIndexes(): void @@ -255,23 +248,21 @@ public function testDeleteIndexes(): void public function testSwapIndexes(): void { - $task = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']]); - $completedTask = $this->client->waitForTask($task->getTaskUid()); + $task = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']])->wait(); self::assertSame(['indexA', 'indexB'], $response['details']['swaps'][0]['indexes']); self::assertSame(['indexC', 'indexD'], $response['details']['swaps'][1]['indexes']); self::assertFalse($response['details']['swaps'][0]['rename']); self::assertFalse($response['details']['swaps'][1]['rename']); -// self::assertInstanceOf(IndexSwapDetails::class, $details = $completedTask->getDetails()); +// self::assertInstanceOf(IndexSwapDetails::class, $details = $task->getDetails()); // self::assertSame([['indexes' => ['indexA', 'indexB']], ['indexes' => ['indexC', 'indexD']]], $details->swaps); } public function testDeleteTasks(): void { - $task = $this->client->deleteTasks((new DeleteTasksQuery())->setUids([1, 2])); - $completedTask = $this->client->waitForTask($task->getTaskUid()); + $task = $this->client->deleteTasks((new DeleteTasksQuery())->setUids([1, 2]))->wait(); - self::assertInstanceOf(TaskDeletionDetails::class, $details = $completedTask->getDetails()); + self::assertInstanceOf(TaskDeletionDetails::class, $details = $task->getDetails()); self::assertSame('?uids=1%2C2', $details->originalFilter); } diff --git a/tests/Endpoints/MultiSearchTest.php b/tests/Endpoints/MultiSearchTest.php index 15ea3cbd..0b0fa85c 100644 --- a/tests/Endpoints/MultiSearchTest.php +++ b/tests/Endpoints/MultiSearchTest.php @@ -22,11 +22,11 @@ final class MultiSearchTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->booksIndex = $this->createEmptyIndex($this->safeIndexName('books')); $this->booksIndex->updateSortableAttributes(['author']); $this->booksIndex->updateFilterableAttributes(['genre']); - $task = $this->booksIndex->updateDocuments(self::DOCUMENTS); - $this->booksIndex->waitForTask($task->getTaskUid()); + $this->booksIndex->updateDocuments(self::DOCUMENTS)->wait(); $this->songsIndex = $this->createEmptyIndex($this->safeIndexName('songs')); $this->songsIndex->updateFilterableAttributes(['duration-float']); @@ -34,8 +34,7 @@ protected function setUp(): void $documents = fread($fileCsv, filesize('./tests/datasets/songs-custom-separator.csv')); fclose($fileCsv); - $task = $this->songsIndex->addDocumentsCsv($documents, null, '|'); - $this->songsIndex->waitForTask($task->getTaskUid()); + $this->songsIndex->addDocumentsCsv($documents, null, '|')->wait(); } public function testSearchQueryData(): void diff --git a/tests/Endpoints/SearchNestedFieldsTest.php b/tests/Endpoints/SearchNestedFieldsTest.php index bc47f78f..7202359c 100644 --- a/tests/Endpoints/SearchNestedFieldsTest.php +++ b/tests/Endpoints/SearchNestedFieldsTest.php @@ -14,9 +14,9 @@ final class SearchNestedFieldsTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName('nestedIndex')); - $task = $this->index->updateDocuments(self::NESTED_DOCUMENTS); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDocuments(self::NESTED_DOCUMENTS)->wait(); } public function testBasicSearchOnNestedFields(): void @@ -65,10 +65,9 @@ public function testSearchOnNestedFieldWithOptions(): void self::assertSame(1, $response['hits'][0]['id']); } - public function testSearchOnNestedFieldWithSearchableAtributes(): void + public function testSearchOnNestedFieldWithSearchableAttributes(): void { - $task = $this->index->updateSearchableAttributes(['title', 'info.comment']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSearchableAttributes(['title', 'info.comment'])->wait(); $response = $this->index->search('An awesome'); @@ -84,10 +83,9 @@ public function testSearchOnNestedFieldWithSearchableAtributes(): void self::assertSame(5, $response['hits'][0]['id']); } - public function testSearchOnNestedFieldWithSortableAtributes(): void + public function testSearchOnNestedFieldWithSortableAttributes(): void { - $task = $this->index->updateSortableAttributes(['info.reviewNb']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSortableAttributes(['info.reviewNb'])->wait(); $response = $this->index->search('An awesome'); @@ -105,13 +103,12 @@ public function testSearchOnNestedFieldWithSortableAtributes(): void self::assertSame(5, $response['hits'][0]['id']); } - public function testSearchOnNestedFieldWithSortableAtributesAndSearchableAttributes(): void + public function testSearchOnNestedFieldWithSortableAttributesAndSearchableAttributes(): void { - $task = $this->index->updateSettings([ + $this->index->updateSettings([ 'searchableAttributes' => ['title', 'info.comment'], 'sortableAttributes' => ['info.reviewNb'], - ]); - $this->index->waitForTask($task->getTaskUid()); + ])->wait(); $response = $this->index->search('An awesome'); diff --git a/tests/Endpoints/SearchTest.php b/tests/Endpoints/SearchTest.php index 149b6dd5..3d7b0428 100644 --- a/tests/Endpoints/SearchTest.php +++ b/tests/Endpoints/SearchTest.php @@ -16,9 +16,9 @@ final class SearchTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); - $task = $this->index->updateDocuments(self::DOCUMENTS); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDocuments(self::DOCUMENTS)->wait(); } public function testBasicSearch(): void @@ -132,8 +132,7 @@ public function testExceptionIfNoIndexWhenSearching(): void { $index = $this->createEmptyIndex($this->safeIndexName('movie-1')); - $task = $index->delete(); - $index->waitForTask($task->getTaskUid()); + $index->delete()->wait(); $this->expectException(ApiException::class); @@ -190,8 +189,7 @@ public function testParametersWithCustomizedCropMarker(): void public function testSearchWithMatchingStrategyALL(): void { - $task = $this->index->updateSearchableAttributes(['comment']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSearchableAttributes(['comment'])->wait(); $response = $this->index->search('another french book', [ 'matchingStrategy' => 'all', @@ -202,8 +200,7 @@ public function testSearchWithMatchingStrategyALL(): void public function testSearchWithMatchingStrategyLAST(): void { - $task = $this->index->updateSearchableAttributes(['comment']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSearchableAttributes(['comment'])->wait(); $response = $this->index->search('french book', [ 'matchingStrategy' => 'last', @@ -260,8 +257,7 @@ public function testParametersWithCustomizedHighlightTag(): void public function testParametersArray(): void { - $task = $this->index->updateFilterableAttributes(['title']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['title'])->wait(); $response = $this->index->search('prince', [ 'limit' => 5, @@ -304,8 +300,7 @@ public function testParametersArray(): void public function testParametersCanBeAStar(): void { - $task = $this->index->updateFilterableAttributes(['title']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['title'])->wait(); $response = $this->index->search('prince', [ 'limit' => 5, @@ -348,8 +343,7 @@ public function testParametersCanBeAStar(): void public function testSearchWithFilterCanBeInt(): void { - $task = $this->index->updateFilterableAttributes(['id', 'genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['id', 'genre'])->wait(); $response = $this->index->search('prince', [ 'filter' => 'id < 12', @@ -371,8 +365,7 @@ public function testSearchWithFilterCanBeInt(): void public function testBasicSearchWithFacetDistribution(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $response = $this->index->search('prince', [ 'facets' => ['genre'], @@ -397,8 +390,7 @@ public function testBasicSearchWithFacetDistribution(): void public function testBasicSearchWithFilters(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $response = $this->index->search('prince', [ 'filter' => [['genre = fantasy']], @@ -419,8 +411,7 @@ public function testBasicSearchWithFilters(): void public function testBasicSearchWithMultipleFilter(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $response = $this->index->search('prince', [ 'filter' => ['genre = fantasy', ['genre = fantasy', 'genre = fantasy']], @@ -441,8 +432,7 @@ public function testBasicSearchWithMultipleFilter(): void public function testCustomSearchWithFilterAndAttributesToRetrieve(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $response = $this->index->search('prince', [ 'filter' => [['genre = fantasy']], @@ -471,18 +461,15 @@ public function testCustomSearchWithFilterAndAttributesToRetrieve(): void public function testSearchSortWithString(): void { - $task = $this->index->updateRankingRules([ + $this->index->updateRankingRules([ 'words', 'typo', 'sort', 'proximity', 'attribute', 'exactness', - ]); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->updateSortableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + ])->wait(); + $this->index->updateSortableAttributes(['genre'])->wait(); $response = $this->index->search('prince', [ 'sort' => ['genre:asc'], @@ -510,11 +497,8 @@ public function testSearchSortWithInt(): void 'proximity', 'attribute', 'exactness', - ]); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->updateSortableAttributes(['id']); - $this->index->waitForTask($task->getTaskUid()); + ])->wait(); + $this->index->updateSortableAttributes(['id'])->wait(); $response = $this->index->search('prince', [ 'sort' => ['id:asc'], @@ -535,18 +519,15 @@ public function testSearchSortWithInt(): void public function testSearchSortWithMultipleParameter(): void { - $task = $this->index->updateRankingRules([ + $this->index->updateRankingRules([ 'words', 'typo', 'sort', 'proximity', 'attribute', 'exactness', - ]); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->updateSortableAttributes(['id', 'title']); - $this->index->waitForTask($task->getTaskUid()); + ])->wait(); + $this->index->updateSortableAttributes(['id', 'title'])->wait(); $response = $this->index->search('prince', [ 'sort' => ['id:asc', 'title:asc'], @@ -671,8 +652,7 @@ function (array $hit): bool { return 'Le Petit Prince' === $hit['title']; } public function testBasicSearchWithFacetsOption(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $response = $this->index->search( 'prince', @@ -689,11 +669,8 @@ public function testBasicSearchWithFacetsOption(): void public function testBasicSearchWithFacetsOptionAndMultipleFacets(): void { - $task = $this->index->addDocuments([['id' => 32, 'title' => 'The Witcher', 'genre' => 'adventure', 'adaptation' => 'video game']]); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->updateFilterableAttributes(['genre', 'adaptation']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->addDocuments([['id' => 32, 'title' => 'The Witcher', 'genre' => 'adventure', 'adaptation' => 'video game']])->wait(); + $this->index->updateFilterableAttributes(['genre', 'adaptation'])->wait(); $response = $this->index->search( 'witch', @@ -714,11 +691,8 @@ public function testVectorSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]]); - $index->waitForTask($task->getTaskUid()); - - $task = $index->updateDocuments(self::VECTOR_MOVIES); - $index->waitForTask($task->getTaskUid()); + $index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3]])->wait(); + $index->updateDocuments(self::VECTOR_MOVIES)->wait(); $response = $index->search('', ['vector' => [-0.5, 0.3, 0.85], 'hybrid' => ['semanticRatio' => 1.0, 'embedder' => 'manual']]); @@ -743,8 +717,7 @@ public function testShowRankingScoreDetails(): void public function testBasicSearchWithTransformFacetsDritributionOptionToFilter(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $filterAllFacets = function (array $facets): array { $filterOneFacet = function (array $facet): array { @@ -775,8 +748,7 @@ function (int $facetValue): bool { return 1 < $facetValue; }, public function testSearchWithAttributesToSearchOn(): void { - $task = $this->index->updateSearchableAttributes(['comment', 'title']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSearchableAttributes(['comment', 'title'])->wait(); $response = $this->index->search('the', ['attributesToSearchOn' => ['comment']]); @@ -802,10 +774,9 @@ public function testSearchWithRankingScoreThreshold(): void self::assertSame(0, $response->getHitsCount()); } - public function testBasicSearchWithTransformFacetsDritributionOptionToMap(): void + public function testBasicSearchWithTransformFacetsDistributionOptionToMap(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $facetsToUpperFunc = function (array $facets): array { $changeOneFacet = function (array $facet): array { @@ -835,10 +806,9 @@ public function testBasicSearchWithTransformFacetsDritributionOptionToMap(): voi self::assertSame(1, $response->getFacetDistribution()['genre']['ADVENTURE']); } - public function testBasicSearchWithTransformFacetsDritributionOptionToOder(): void + public function testBasicSearchWithTransformFacetsDistributionOptionToOrder(): void { - $task = $this->index->updateFilterableAttributes(['genre']); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateFilterableAttributes(['genre'])->wait(); $facetsToUpperFunc = function (array $facets): array { $sortOneFacet = function (array $facet): array { @@ -871,8 +841,7 @@ public function testSearchAndRetrieveFacetStats(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateFilterableAttributes(['info.reviewNb']); - $task = $this->index->updateDocuments(self::NESTED_DOCUMENTS); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDocuments(self::NESTED_DOCUMENTS)->wait(); $response = $this->index->search( null, @@ -887,8 +856,7 @@ public function testSearchWithDistinctAttribute(): void $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateFilterableAttributes(['genre']); - $task = $this->index->updateDocuments(self::DOCUMENTS); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDocuments(self::DOCUMENTS)->wait(); $response = $this->index->search(null, [ 'distinct' => 'genre', @@ -917,8 +885,7 @@ public function testSearchWithLocales(): void { $this->index = $this->createEmptyIndex($this->safeIndexName()); $this->index->updateDocuments(self::DOCUMENTS); - $task = $this->index->updateLocalizedAttributes([['attributePatterns' => ['title', 'comment'], 'locales' => ['fra', 'eng']]]); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateLocalizedAttributes([['attributePatterns' => ['title', 'comment'], 'locales' => ['fra', 'eng']]])->wait(); $response = $this->index->search('french', [ 'locales' => ['fra', 'eng'], diff --git a/tests/Endpoints/SimilarDocumentsTest.php b/tests/Endpoints/SimilarDocumentsTest.php index c2315512..d617fab9 100644 --- a/tests/Endpoints/SimilarDocumentsTest.php +++ b/tests/Endpoints/SimilarDocumentsTest.php @@ -22,8 +22,7 @@ protected function setUp(): void public function testBasicSearchWithSimilarDocuments(): void { - $task = $this->index->updateSettings(['embedders' => ['manual' => ['source' => 'userProvided', 'dimensions' => 3]]]); - $this->client->waitForTask($task->getTaskUid()); + $this->index->updateSettings(['embedders' => ['manual' => ['source' => 'userProvided', 'dimensions' => 3]]])->wait(); $response = $this->index->search('room'); diff --git a/tests/Endpoints/TasksTest.php b/tests/Endpoints/TasksTest.php index a6df8ed3..c7a3f220 100644 --- a/tests/Endpoints/TasksTest.php +++ b/tests/Endpoints/TasksTest.php @@ -116,12 +116,10 @@ public function testCancelTasksWithFilter(): void { $date = new \DateTime('yesterday'); $query = http_build_query(['afterEnqueuedAt' => $date->format(\DateTime::RFC3339)]); - $task = $this->client->cancelTasks((new CancelTasksQuery())->setAfterEnqueuedAt($date)); + $task = $this->client->cancelTasks((new CancelTasksQuery())->setAfterEnqueuedAt($date))->wait(); - $cancelTask = $this->client->waitForTask($task->getTaskUid()); - self::assertSame(TaskStatus::Succeeded, $cancelTask->getStatus()); - - self::assertInstanceOf(TaskCancelationDetails::class, $details = $cancelTask->getDetails()); + self::assertSame(TaskStatus::Succeeded, $task->getStatus()); + self::assertInstanceOf(TaskCancelationDetails::class, $details = $task->getDetails()); self::assertSame('?'.$query, $details->originalFilter); } @@ -154,8 +152,7 @@ public function testExceptionIfNoTaskIdWhenGetting(): void private function seedIndex(): array { $task = $this->index->updateDocuments(self::DOCUMENTS); - $completedTask = $this->client->waitForTask($task->getTaskUid()); - return [$task, $completedTask]; + return [$task, $task->wait()]; } } diff --git a/tests/Endpoints/TenantTokenTest.php b/tests/Endpoints/TenantTokenTest.php index 338c4aec..417b3920 100644 --- a/tests/Endpoints/TenantTokenTest.php +++ b/tests/Endpoints/TenantTokenTest.php @@ -42,8 +42,7 @@ protected function tearDown(): void public function testGenerateTenantTokenWithSearchRulesOnly(): void { - $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($task->getTaskUid()); + $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS)->wait(); $token = $this->privateClient->generateTenantToken($this->key->getUid(), ['*']); $tokenClient = new Client($this->host, $token); @@ -55,8 +54,7 @@ public function testGenerateTenantTokenWithSearchRulesOnly(): void public function testGenerateTenantTokenWithSearchRulesAsObject(): void { - $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($task->getTaskUid()); + $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS)->wait(); $token = $this->privateClient->generateTenantToken($this->key->getUid(), (object) ['*' => (object) []]); $tokenClient = new Client($this->host, $token); @@ -68,12 +66,10 @@ public function testGenerateTenantTokenWithSearchRulesAsObject(): void public function testGenerateTenantTokenWithFilter(): void { - $task = $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS); - $this->client->waitForTask($task->getTaskUid()); - $taskFromFilter = $this->client->index('tenantToken')->updateFilterableAttributes([ + $this->client->index('tenantToken')->addDocuments(self::DOCUMENTS)->wait(); + $this->client->index('tenantToken')->updateFilterableAttributes([ 'id', - ]); - $this->client->waitForTask($taskFromFilter->getTaskUid()); + ])->wait(); $token = $this->privateClient->generateTenantToken($this->key->getUid(), (object) ['tenantToken' => (object) ['filter' => 'id > 10']]); $tokenClient = new Client($this->host, $token); diff --git a/tests/MockTask.php b/tests/MockTask.php index cd5e3b92..603021b1 100644 --- a/tests/MockTask.php +++ b/tests/MockTask.php @@ -16,7 +16,8 @@ public static function create( ?string $indexUid = null, TaskStatus $status = TaskStatus::Enqueued, \DateTimeImmutable $enqueuedAt = new \DateTimeImmutable('2025-04-09T07:09:13.867326401Z'), + ?\Closure $await = null, ): Task { - return new Task($taskUid, $indexUid, $status, $type, $enqueuedAt); + return new Task($taskUid, $indexUid, $status, $type, $enqueuedAt, await: $await); } } diff --git a/tests/Settings/DisplayedAttributesTest.php b/tests/Settings/DisplayedAttributesTest.php index 86ca2367..779cd2b8 100644 --- a/tests/Settings/DisplayedAttributesTest.php +++ b/tests/Settings/DisplayedAttributesTest.php @@ -25,9 +25,7 @@ public function testUpdateDisplayedAttributes(): void $newAttributes = ['title']; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateDisplayedAttributes($newAttributes); - - $index->waitForTask($task->getTaskUid()); + $index->updateDisplayedAttributes($newAttributes)->wait(); $displayedAttributes = $index->getDisplayedAttributes(); @@ -39,12 +37,8 @@ public function testResetDisplayedAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = ['title']; - $task = $index->updateDisplayedAttributes($newAttributes); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetDisplayedAttributes(); - - $index->waitForTask($task->getTaskUid()); + $index->updateDisplayedAttributes($newAttributes); + $index->resetDisplayedAttributes()->wait(); $displayedAttributes = $index->getDisplayedAttributes(); self::assertSame(['*'], $displayedAttributes); diff --git a/tests/Settings/DistinctAttributeTest.php b/tests/Settings/DistinctAttributeTest.php index e9a675d3..c7ecc016 100644 --- a/tests/Settings/DistinctAttributeTest.php +++ b/tests/Settings/DistinctAttributeTest.php @@ -14,6 +14,7 @@ final class DistinctAttributeTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); } @@ -28,8 +29,7 @@ public function testUpdateDistinctAttribute(): void { $distinctAttribute = 'description'; - $task = $this->index->updateDistinctAttribute($distinctAttribute); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDistinctAttribute($distinctAttribute)->wait(); self::assertSame($distinctAttribute, $this->index->getDistinctAttribute()); } @@ -38,11 +38,8 @@ public function testResetDistinctAttribute(): void { $distinctAttribute = 'description'; - $task = $this->index->updateDistinctAttribute($distinctAttribute); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->resetDistinctAttribute(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDistinctAttribute($distinctAttribute)->wait(); + $this->index->resetDistinctAttribute()->wait(); self::assertNull($this->index->getDistinctAttribute()); } diff --git a/tests/Settings/EmbeddersTest.php b/tests/Settings/EmbeddersTest.php index f4e890bb..f68eac48 100644 --- a/tests/Settings/EmbeddersTest.php +++ b/tests/Settings/EmbeddersTest.php @@ -18,6 +18,7 @@ final class EmbeddersTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); } @@ -32,17 +33,15 @@ public function testUpdateEmbedders(): void { $newEmbedders = ['manual' => ['source' => 'userProvided', 'dimensions' => 3, 'binaryQuantized' => true]]; - $task = $this->index->updateEmbedders($newEmbedders); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateEmbedders($newEmbedders)->wait(); self::assertSame($newEmbedders, $this->index->getEmbedders()); } public function testResetEmbedders(): void { - $task = $this->index->resetEmbedders(); - - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateEmbedders(['manual' => ['source' => 'userProvided', 'dimensions' => 3, 'binaryQuantized' => true]])->wait(); + $this->index->resetEmbedders()->wait(); self::assertSame(self::DEFAULT_EMBEDDER, $this->index->getEmbedders()); } @@ -55,15 +54,13 @@ public function testHuggingFacePooling(): void 'pooling' => 'useModel', ]; - $task = $this->index->updateEmbedders([ + $this->index->updateEmbedders([ 'embedder_name' => [ 'source' => 'huggingFace', 'model' => 'sentence-transformers/all-MiniLM-L6-v2', 'pooling' => 'useModel', ], - ]); - - $this->index->waitForTask($task->getTaskUid()); + ])->wait(); $embedders = $this->index->getEmbedders(); diff --git a/tests/Settings/FacetSearchTest.php b/tests/Settings/FacetSearchTest.php index 6bf107b7..49b92482 100644 --- a/tests/Settings/FacetSearchTest.php +++ b/tests/Settings/FacetSearchTest.php @@ -21,8 +21,7 @@ public function testUpdateFacetSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateFacetSearch(false); - $index->waitForTask($task->getTaskUid()); + $index->updateFacetSearch(false)->wait(); self::assertFalse($index->getFacetSearch()); } @@ -31,11 +30,8 @@ public function testResetFacetSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateFacetSearch(false); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetFacetSearch(); - $index->waitForTask($task->getTaskUid()); + $index->updateFacetSearch(false)->wait(); + $index->resetFacetSearch()->wait(); self::assertTrue($index->getFacetSearch()); } diff --git a/tests/Settings/FacetingAttributesTest.php b/tests/Settings/FacetingAttributesTest.php index 1d9d93e7..cda81b63 100644 --- a/tests/Settings/FacetingAttributesTest.php +++ b/tests/Settings/FacetingAttributesTest.php @@ -25,8 +25,7 @@ public function testUpdateFacetingAttributes(): void $newAttributes = ['sortFacetValuesBy' => ['*' => 'count']]; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateFaceting($newAttributes); - $index->waitForTask($task->getTaskUid()); + $index->updateFaceting($newAttributes)->wait(); self::assertSame([ 'maxValuesPerFacet' => 100, @@ -39,11 +38,8 @@ public function testResetFaceting(): void $newAttributes = ['sortFacetValuesBy' => ['*' => 'count']]; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateFaceting($newAttributes); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetFaceting(); - $index->waitForTask($task->getTaskUid()); + $index->updateFaceting($newAttributes)->wait(); + $index->resetFaceting()->wait(); self::assertSame([ 'maxValuesPerFacet' => 100, diff --git a/tests/Settings/FilterableAttributesTest.php b/tests/Settings/FilterableAttributesTest.php index 16e34a45..30d80dcf 100644 --- a/tests/Settings/FilterableAttributesTest.php +++ b/tests/Settings/FilterableAttributesTest.php @@ -20,8 +20,7 @@ public function testUpdateFilterableAttributes(): void $expectedAttributes = ['title']; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateFilterableAttributes($expectedAttributes); - $index->waitForTask($task->getTaskUid()); + $index->updateFilterableAttributes($expectedAttributes)->wait(); self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } @@ -31,11 +30,8 @@ public function testResetFilterableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = ['title']; - $task = $index->updateFilterableAttributes($newAttributes); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetFilterableAttributes(); - $index->waitForTask($task->getTaskUid()); + $index->updateFilterableAttributes($newAttributes)->wait(); + $index->resetFilterableAttributes()->wait(); self::assertEmpty($index->getFilterableAttributes()); } @@ -58,8 +54,7 @@ public function testUpdateGranularFilterableAttributes(): void ], ]; - $task = $index->updateFilterableAttributes($expectedAttributes); - $index->waitForTask($task->getTaskUid()); + $index->updateFilterableAttributes($expectedAttributes)->wait(); self::assertSame($expectedAttributes, $index->getFilterableAttributes()); } @@ -68,13 +63,11 @@ public function testUpdateGeoWithGranularFilterableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateFilterableAttributes([ + $index->updateFilterableAttributes([ [ 'attributePatterns' => ['_geo'], ], - ]); - - $index->waitForTask($task->getTaskUid()); + ])->wait(); self::assertSame([ [ diff --git a/tests/Settings/LocalizedAttributesTest.php b/tests/Settings/LocalizedAttributesTest.php index bb53987d..f5a1e9a7 100644 --- a/tests/Settings/LocalizedAttributesTest.php +++ b/tests/Settings/LocalizedAttributesTest.php @@ -25,9 +25,7 @@ public function testUpdateLocalizedAttributes(): void $newAttributes = [['attributePatterns' => ['doggo'], 'locales' => ['fra']]]; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateLocalizedAttributes($newAttributes); - - $index->waitForTask($task->getTaskUid()); + $index->updateLocalizedAttributes($newAttributes)->wait(); $localizedAttributes = $index->getLocalizedAttributes(); @@ -39,11 +37,8 @@ public function testResetLocalizedAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = [['attributePatterns' => ['doggo'], 'locales' => ['fra']]]; - $task = $index->updateLocalizedAttributes($newAttributes); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetLocalizedAttributes(); - $index->waitForTask($task->getTaskUid()); + $index->updateLocalizedAttributes($newAttributes)->wait(); + $index->resetLocalizedAttributes()->wait(); $localizedAttributes = $index->getLocalizedAttributes(); self::assertNull($localizedAttributes); diff --git a/tests/Settings/NonSeparatorTokensTest.php b/tests/Settings/NonSeparatorTokensTest.php index a41019fe..5a8d44cd 100644 --- a/tests/Settings/NonSeparatorTokensTest.php +++ b/tests/Settings/NonSeparatorTokensTest.php @@ -34,16 +34,15 @@ public function testUpdateNonSeparatorTokens(): void '|', ]; - $task = $this->index->updateNonSeparatorTokens($newNonSeparatorTokens); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateNonSeparatorTokens($newNonSeparatorTokens)->wait(); self::assertSame($newNonSeparatorTokens, $this->index->getNonSeparatorTokens()); } public function testResetNonSeparatorTokens(): void { - $task = $this->index->resetNonSeparatorTokens(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateNonSeparatorTokens(['/'])->wait(); + $this->index->resetNonSeparatorTokens()->wait(); self::assertSame(self::DEFAULT_NON_SEPARATOR_TOKENS, $this->index->getNonSeparatorTokens()); } diff --git a/tests/Settings/PaginationTest.php b/tests/Settings/PaginationTest.php index 6a863f82..7e3f2471 100644 --- a/tests/Settings/PaginationTest.php +++ b/tests/Settings/PaginationTest.php @@ -18,6 +18,7 @@ final class PaginationTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); } @@ -30,21 +31,15 @@ public function testGetDefaultPagination(): void public function testUpdatePagination(): void { - $task = $this->index->updatePagination(['maxTotalHits' => 100]); - - $this->index->waitForTask($task->getTaskUid()); + $this->index->updatePagination(['maxTotalHits' => 100])->wait(); self::assertSame(['maxTotalHits' => 100], $this->index->getPagination()); } public function testResetPagination(): void { - $task = $this->index->updatePagination(['maxTotalHits' => 100]); - - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->resetPagination(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updatePagination(['maxTotalHits' => 100])->wait(); + $this->index->resetPagination()->wait(); self::assertSame(self::DEFAULT_PAGINATION, $this->index->getPagination()); } diff --git a/tests/Settings/PrefixSearchTest.php b/tests/Settings/PrefixSearchTest.php index a160c959..e2431789 100644 --- a/tests/Settings/PrefixSearchTest.php +++ b/tests/Settings/PrefixSearchTest.php @@ -20,9 +20,7 @@ public function testGetDefaultPrefixSearch(): void public function testUpdatePrefixSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - - $task = $index->updatePrefixSearch('disabled'); - $index->waitForTask($task->getTaskUid()); + $index->updatePrefixSearch('disabled')->wait(); self::assertSame('disabled', $index->getPrefixSearch()); } @@ -31,11 +29,8 @@ public function testResetPrefixSearch(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updatePrefixSearch('disabled'); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetPrefixSearch(); - $index->waitForTask($task->getTaskUid()); + $index->updatePrefixSearch('disabled')->wait(); + $index->resetPrefixSearch()->wait(); self::assertSame('indexingTime', $index->getPrefixSearch()); } diff --git a/tests/Settings/ProximityPrecisionTest.php b/tests/Settings/ProximityPrecisionTest.php index 6b172c0b..c3fdc0e0 100644 --- a/tests/Settings/ProximityPrecisionTest.php +++ b/tests/Settings/ProximityPrecisionTest.php @@ -14,6 +14,7 @@ final class ProximityPrecisionTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); } @@ -26,19 +27,15 @@ public function testGetDefaultProximityPrecision(): void public function testUpdateProximityPrecision(): void { - $task = $this->index->updateProximityPrecision('byAttribute'); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateProximityPrecision('byAttribute')->wait(); self::assertSame('byAttribute', $this->index->getProximityPrecision()); } public function testResetProximityPrecision(): void { - $task = $this->index->updateProximityPrecision('byAttribute'); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->resetProximityPrecision(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateProximityPrecision('byAttribute')->wait(); + $this->index->resetProximityPrecision()->wait(); self::assertSame('byWord', $this->index->getProximityPrecision()); } diff --git a/tests/Settings/RankingRulesTest.php b/tests/Settings/RankingRulesTest.php index e18be54a..e32c8da5 100644 --- a/tests/Settings/RankingRulesTest.php +++ b/tests/Settings/RankingRulesTest.php @@ -41,9 +41,7 @@ public function testUpdateRankingRules(): void 'description:desc', ]; - $task = $this->index->updateRankingRules($newRankingRules); - - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateRankingRules($newRankingRules)->wait(); $rankingRules = $this->index->getRankingRules(); @@ -52,9 +50,9 @@ public function testUpdateRankingRules(): void public function testResetRankingRules(): void { - $task = $this->index->resetRankingRules(); + $this->index->updateRankingRules(['title:asc'])->wait(); + $this->index->resetRankingRules()->wait(); - $this->index->waitForTask($task->getTaskUid()); $rankingRules = $this->index->getRankingRules(); self::assertSame(self::DEFAULT_RANKING_RULES, $rankingRules); diff --git a/tests/Settings/SearchCutoffMsTest.php b/tests/Settings/SearchCutoffMsTest.php index 01d087e5..128765c3 100644 --- a/tests/Settings/SearchCutoffMsTest.php +++ b/tests/Settings/SearchCutoffMsTest.php @@ -14,6 +14,7 @@ final class SearchCutoffMsTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); } @@ -26,19 +27,15 @@ public function testGetDefaultSearchCutoffMs(): void public function testUpdateSearchCutoffMs(): void { - $task = $this->index->updateSearchCutoffMs(50); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSearchCutoffMs(50)->wait(); self::assertSame(50, $this->index->getSearchCutoffMs()); } public function testResetSearchCutoffMs(): void { - $task = $this->index->updateSearchCutoffMs(50); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->resetSearchCutoffMs(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSearchCutoffMs(50)->wait(); + $this->index->resetSearchCutoffMs()->wait(); self::assertNull($this->index->getSearchCutoffMs()); } diff --git a/tests/Settings/SearchableAttributesTest.php b/tests/Settings/SearchableAttributesTest.php index ac7f55cd..46666ea8 100644 --- a/tests/Settings/SearchableAttributesTest.php +++ b/tests/Settings/SearchableAttributesTest.php @@ -28,8 +28,7 @@ public function testUpdateSearchableAttributes(): void 'description', ]; - $task = $indexA->updateSearchableAttributes($searchableAttributes); - $indexA->waitForTask($task->getTaskUid()); + $indexA->updateSearchableAttributes($searchableAttributes)->wait(); self::assertSame($searchableAttributes, $indexA->getSearchableAttributes()); } @@ -38,8 +37,7 @@ public function testResetSearchableAttributes(): void { $index = $this->createEmptyIndex($this->safeIndexName('books-1')); - $task = $index->resetSearchableAttributes(); - $index->waitForTask($task->getTaskUid()); + $index->resetSearchableAttributes()->wait(); self::assertSame(['*'], $index->getSearchableAttributes()); } diff --git a/tests/Settings/SeparatorTokensTest.php b/tests/Settings/SeparatorTokensTest.php index 5f7b765e..b9023623 100644 --- a/tests/Settings/SeparatorTokensTest.php +++ b/tests/Settings/SeparatorTokensTest.php @@ -34,16 +34,15 @@ public function testUpdateSeparatorTokens(): void '|', ]; - $task = $this->index->updateSeparatorTokens($newSeparatorTokens); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSeparatorTokens($newSeparatorTokens)->wait(); self::assertSame($newSeparatorTokens, $this->index->getSeparatorTokens()); } public function testResetSeparatorTokens(): void { - $task = $this->index->resetSeparatorTokens(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSeparatorTokens(['/'])->wait(); + $this->index->resetSeparatorTokens()->wait(); self::assertSame(self::DEFAULT_SEPARATOR_TOKENS, $this->index->getSeparatorTokens()); } diff --git a/tests/Settings/SettingsTest.php b/tests/Settings/SettingsTest.php index 7dee217e..d73f6ba1 100644 --- a/tests/Settings/SettingsTest.php +++ b/tests/Settings/SettingsTest.php @@ -85,14 +85,13 @@ public function testUpdateSettings(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateSettings([ + $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], 'facetSearch' => false, 'prefixSearch' => 'disabled', - ]); - $index->waitForTask($task->getTaskUid()); + ])->wait(); $settings = $index->getSettings(); @@ -129,18 +128,16 @@ public function testUpdateSettingsWithoutOverwritingThem(): void $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateSettings([ + $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], 'typoTolerance' => $new_typo_tolerance, - ]); - $index->waitForTask($task->getTaskUid()); + ])->wait(); - $task = $index->updateSettings([ + $index->updateSettings([ 'searchableAttributes' => ['title'], - ]); - $index->waitForTask($task->getTaskUid()); + ])->wait(); $settings = $index->getSettings(); @@ -163,15 +160,13 @@ public function testResetSettings(): void { $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateSettings([ + $index->updateSettings([ 'distinctAttribute' => 'title', 'rankingRules' => ['title:asc', 'typo'], 'stopWords' => ['the'], - ]); - $index->waitForTask($task->getTaskUid()); + ])->wait(); - $task = $index->resetSettings(); - $index->waitForTask($task->getTaskUid()); + $index->resetSettings()->wait(); $settings = $index->getSettings(); diff --git a/tests/Settings/SortableAttributesTest.php b/tests/Settings/SortableAttributesTest.php index 7d8a2ec4..30a41031 100644 --- a/tests/Settings/SortableAttributesTest.php +++ b/tests/Settings/SortableAttributesTest.php @@ -20,8 +20,7 @@ public function testUpdateSortableAttributes(): void $newAttributes = ['title']; $index = $this->createEmptyIndex($this->safeIndexName()); - $task = $index->updateSortableAttributes($newAttributes); - $index->waitForTask($task->getTaskUid()); + $index->updateSortableAttributes($newAttributes)->wait(); self::assertSame($newAttributes, $index->getSortableAttributes()); } @@ -31,11 +30,8 @@ public function testResetSortableAttributes(): void $index = $this->createEmptyIndex($this->safeIndexName()); $newAttributes = ['title']; - $task = $index->updateSortableAttributes($newAttributes); - $index->waitForTask($task->getTaskUid()); - - $task = $index->resetSortableAttributes(); - $index->waitForTask($task->getTaskUid()); + $index->updateSortableAttributes($newAttributes)->wait(); + $index->resetSortableAttributes()->wait(); self::assertEmpty($index->getSortableAttributes()); } diff --git a/tests/Settings/StopWordsTest.php b/tests/Settings/StopWordsTest.php index 048dbe0e..888d260b 100644 --- a/tests/Settings/StopWordsTest.php +++ b/tests/Settings/StopWordsTest.php @@ -27,20 +27,15 @@ public function testGetDefaultStopWords(): void public function testUpdateStopWords(): void { $newStopWords = ['the']; - $task = $this->index->updateStopWords($newStopWords); - - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateStopWords($newStopWords)->wait(); self::assertSame($newStopWords, $this->index->getStopWords()); } public function testResetStopWords(): void { - $task = $this->index->updateStopWords(['the']); - $this->index->waitForTask($task->getTaskUid()); - - $task = $this->index->resetStopWords(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateStopWords(['the'])->wait(); + $this->index->resetStopWords()->wait(); self::assertEmpty($this->index->getStopWords()); } diff --git a/tests/Settings/SynonymsTest.php b/tests/Settings/SynonymsTest.php index bd5f63d9..c47a2b0d 100644 --- a/tests/Settings/SynonymsTest.php +++ b/tests/Settings/SynonymsTest.php @@ -28,8 +28,7 @@ public function testUpdateSynonyms(): void 'hp' => ['harry potter'], ]; - $task = $this->index->updateSynonyms($newSynonyms); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSynonyms($newSynonyms)->wait(); self::assertSame($newSynonyms, $this->index->getSynonyms()); } @@ -38,21 +37,15 @@ public function testUpdateSynonymsWithEmptyArray(): void { $newSynonyms = []; - $task = $this->index->updateSynonyms($newSynonyms); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSynonyms($newSynonyms)->wait(); self::assertSame($newSynonyms, $this->index->getSynonyms()); } public function testResetSynonyms(): void { - $task = $this->index->updateSynonyms([ - 'hp' => ['harry potter'], - ]); - $this->index->waitForTask($task->getTaskUid()); - $task = $this->index->resetSynonyms(); - - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateSynonyms(['hp' => ['harry potter']])->wait(); + $this->index->resetSynonyms()->wait(); self::assertEmpty($this->index->getSynonyms()); } diff --git a/tests/Settings/TypoToleranceTest.php b/tests/Settings/TypoToleranceTest.php index 11fefb82..072f6cff 100644 --- a/tests/Settings/TypoToleranceTest.php +++ b/tests/Settings/TypoToleranceTest.php @@ -47,8 +47,7 @@ public function testUpdateTypoTolerance(): void 'disableOnAttributes' => ['title'], 'disableOnNumbers' => true, ]; - $task = $this->index->updateTypoTolerance($newTypoTolerance); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateTypoTolerance($newTypoTolerance)->wait(); $typoTolerance = $this->index->getTypoTolerance(); self::assertSame($newTypoTolerance, $typoTolerance); @@ -56,8 +55,7 @@ public function testUpdateTypoTolerance(): void public function testResetTypoTolerance(): void { - $task = $this->index->resetTypoTolerance(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->resetTypoTolerance()->wait(); $typoTolerance = $this->index->getTypoTolerance(); self::assertSame(self::DEFAULT_TYPO_TOLERANCE, $typoTolerance); diff --git a/tests/Settings/WordDictionaryTest.php b/tests/Settings/WordDictionaryTest.php index 19068742..8f1a5e46 100644 --- a/tests/Settings/WordDictionaryTest.php +++ b/tests/Settings/WordDictionaryTest.php @@ -31,16 +31,14 @@ public function testUpdateWordDictionary(): void 'J. R. R.', ]; - $task = $this->index->updateDictionary($newWordDictionary); - $this->index->waitForTask($task->getTaskUid()); + $this->index->updateDictionary($newWordDictionary)->wait(); self::assertSame($newWordDictionary, $this->index->getDictionary()); } public function testResetWordDictionary(): void { - $task = $this->index->resetDictionary(); - $this->index->waitForTask($task->getTaskUid()); + $this->index->resetDictionary()->wait(); self::assertSame(self::DEFAULT_WORD_DICTIONARY, $this->index->getDictionary()); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 29d5e023..c73e9eb6 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -88,13 +88,10 @@ protected function setUp(): void protected function tearDown(): void { $indexes = $this->client->getIndexes((new IndexesQuery())->setLimit(100))->getResults(); - $tasks = []; foreach ($indexes as $index) { - $tasks[] = $index->delete()->getTaskUid(); + $index->delete()->wait(); } - - $this->client->waitForTasks($tasks); } public function assertFinitePagination(array $response): void @@ -133,8 +130,7 @@ public function assertEstimatedPagination(array $response): void public function createEmptyIndex($indexName, $options = []): Indexes { - $task = $this->client->createIndex($indexName, $options); - $this->client->waitForTask($task->getTaskUid()); + $task = $this->client->createIndex($indexName, $options)->wait(); return $this->client->getIndex($task->getIndexUid()); } From e5c7ba6ed258695f07f38a276f1c03cf3c4eceae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Tue, 3 Jun 2025 15:44:32 +0300 Subject: [PATCH 35/51] Use `str_contains` --- src/Http/Client.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Http/Client.php b/src/Http/Client.php index d0023153..cd54d7d7 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -260,10 +260,6 @@ private function parseResponse(ResponseInterface $response) */ private function isJSONResponse(array $headerValues): bool { - $filteredHeaders = array_filter($headerValues, static function (string $headerValue) { - return false !== strpos($headerValue, 'application/json'); - }); - - return \count($filteredHeaders) > 0; + return [] !== array_filter($headerValues, static fn (string $v) => str_contains($v, 'application/json')); } } From bfb0a87b7c6f800c46496cf1573ed6fd2b47b349 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 4 Jun 2025 06:22:36 +0300 Subject: [PATCH 36/51] Fix another review comment --- tests/Contracts/TaskTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Contracts/TaskTest.php b/tests/Contracts/TaskTest.php index cb71522e..0e1d7021 100644 --- a/tests/Contracts/TaskTest.php +++ b/tests/Contracts/TaskTest.php @@ -42,9 +42,9 @@ public function testCreate(): void self::assertSame('documents', $task->getIndexUid()); self::assertSame(TaskStatus::Failed, $task->getStatus()); self::assertSame(TaskType::IndexCreation, $task->getType()); - self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.236789'), $task->getEnqueuedAt()); - self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.555566+0000'), $task->getStartedAt()); - self::assertEquals(new \DateTimeImmutable('+2025-04-09T10:28:12.666677+0000'), $task->getFinishedAt()); + self::assertEquals(new \DateTimeImmutable('2025-04-09T10:28:12.236789'), $task->getEnqueuedAt()); + self::assertEquals(new \DateTimeImmutable('2025-04-09T10:28:12.555566+0000'), $task->getStartedAt()); + self::assertEquals(new \DateTimeImmutable('2025-04-09T10:28:12.666677+0000'), $task->getFinishedAt()); self::assertSame('PT0.184408715S', $task->getDuration()); self::assertSame(123, $task->getCanceledBy()); self::assertSame(666, $task->getBatchUid()); From 5a7a310ab6027276571b47b5942c8694db9881bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 4 Jun 2025 07:29:56 +0300 Subject: [PATCH 37/51] Avoid count --- src/Endpoints/Indexes.php | 4 ++-- src/Http/Client.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index f934f889..93813f04 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -171,8 +171,8 @@ public function getTasks(?TasksQuery $options = null): TasksResults { $options = $options ?? new TasksQuery(); - if (\count($options->getIndexUids()) > 0) { - $options->setIndexUids(array_merge([$this->uid], $options->getIndexUids())); + if ($options->getIndexUids() !== []) { + $options->setIndexUids([$this->uid, ...$options->getIndexUids()]); } else { $options->setIndexUids([$this->uid]); } diff --git a/src/Http/Client.php b/src/Http/Client.php index cd54d7d7..71a7c203 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -224,7 +224,7 @@ private function buildQueryString(array $queryParams = []): string } } - return \count($queryParams) > 0 ? '?'.http_build_query($queryParams) : ''; + return $queryParams !== [] ? '?'.http_build_query($queryParams) : ''; } /** From d975de020223c0aff48f300b8fa70462ad1bb3d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 4 Jun 2025 07:30:48 +0300 Subject: [PATCH 38/51] Always use JSON_THROW_ON_ERROR --- src/Search/FacetSearchResult.php | 2 +- src/Search/SearchResult.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Search/FacetSearchResult.php b/src/Search/FacetSearchResult.php index 24d3774d..ab85b5c1 100644 --- a/src/Search/FacetSearchResult.php +++ b/src/Search/FacetSearchResult.php @@ -47,7 +47,7 @@ public function toArray(): array public function toJSON(): string { - return json_encode($this->toArray(), JSON_PRETTY_PRINT); + return json_encode($this->toArray(), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); } public function getIterator(): \ArrayIterator diff --git a/src/Search/SearchResult.php b/src/Search/SearchResult.php index 3873a72b..449833cf 100644 --- a/src/Search/SearchResult.php +++ b/src/Search/SearchResult.php @@ -245,7 +245,7 @@ public function toArray(): array public function toJSON(): string { - return json_encode($this->toArray(), JSON_PRETTY_PRINT); + return json_encode($this->toArray(), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); } public function getIterator(): \ArrayIterator From c51d9ab57a4224de2199df12a18d0bdb48b6ff47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Wed, 4 Jun 2025 07:32:56 +0300 Subject: [PATCH 39/51] Fix CS --- src/Endpoints/Indexes.php | 2 +- src/Http/Client.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Endpoints/Indexes.php b/src/Endpoints/Indexes.php index 93813f04..0aba5c3c 100644 --- a/src/Endpoints/Indexes.php +++ b/src/Endpoints/Indexes.php @@ -171,7 +171,7 @@ public function getTasks(?TasksQuery $options = null): TasksResults { $options = $options ?? new TasksQuery(); - if ($options->getIndexUids() !== []) { + if ([] !== $options->getIndexUids()) { $options->setIndexUids([$this->uid, ...$options->getIndexUids()]); } else { $options->setIndexUids([$this->uid]); diff --git a/src/Http/Client.php b/src/Http/Client.php index 71a7c203..243016cb 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -224,7 +224,7 @@ private function buildQueryString(array $queryParams = []): string } } - return $queryParams !== [] ? '?'.http_build_query($queryParams) : ''; + return [] !== $queryParams ? '?'.http_build_query($queryParams) : ''; } /** From 4bb394b4285f2fdb328188e91e96d7b729ad1dd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Tue, 10 Jun 2025 07:40:53 +0300 Subject: [PATCH 40/51] Fix lint --- src/Http/Serialize/Json.php | 2 +- src/Http/Serialize/SerializerInterface.php | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Http/Serialize/Json.php b/src/Http/Serialize/Json.php index 97ac79e6..8bf9f56a 100644 --- a/src/Http/Serialize/Json.php +++ b/src/Http/Serialize/Json.php @@ -6,7 +6,7 @@ class Json implements SerializerInterface { - public function serialize(mixed $data): string|bool + public function serialize(mixed $data): string { return json_encode($data, JSON_THROW_ON_ERROR); } diff --git a/src/Http/Serialize/SerializerInterface.php b/src/Http/Serialize/SerializerInterface.php index c8d3861f..941f25e6 100644 --- a/src/Http/Serialize/SerializerInterface.php +++ b/src/Http/Serialize/SerializerInterface.php @@ -11,11 +11,9 @@ interface SerializerInterface * * @param string|int|float|bool|array|null $data * - * @return string|bool - * * @throws \JsonException */ - public function serialize(mixed $data): string|bool; + public function serialize(mixed $data): string; /** * Unserialize the given string. From 397cd4b201534ca4c04a32a7b3d332d4649de704 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Tue, 10 Jun 2025 07:46:26 +0300 Subject: [PATCH 41/51] Fix test --- tests/Settings/TypoToleranceTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Settings/TypoToleranceTest.php b/tests/Settings/TypoToleranceTest.php index 072f6cff..e15bd108 100644 --- a/tests/Settings/TypoToleranceTest.php +++ b/tests/Settings/TypoToleranceTest.php @@ -25,6 +25,7 @@ final class TypoToleranceTest extends TestCase protected function setUp(): void { parent::setUp(); + $this->index = $this->createEmptyIndex($this->safeIndexName()); } From db465701c1a0936282e57addaf2c5d7de2ad6709 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:30:38 +0200 Subject: [PATCH 42/51] Fix code review --- src/Endpoints/TenantToken.php | 2 +- src/functions.php | 8 ++++++++ tests/Endpoints/DocumentsTest.php | 14 +++++++------- tests/Endpoints/IndexTest.php | 3 --- tests/Endpoints/SearchTest.php | 2 +- 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/Endpoints/TenantToken.php b/src/Endpoints/TenantToken.php index 9158e912..13806e7b 100644 --- a/src/Endpoints/TenantToken.php +++ b/src/Endpoints/TenantToken.php @@ -23,7 +23,7 @@ private function validateTenantTokenArguments(array|object $searchRules, array $ if (!isset($options['apiKey']) || ('' === $options['apiKey'] || \strlen($options['apiKey']) <= 8)) { throw InvalidArgumentException::emptyArgument('api key'); } - if ([] === $searchRules) { + if ([] === (array) $searchRules) { throw InvalidArgumentException::emptyArgument('search rules'); } if (isset($options['expiresAt']) && new \DateTimeImmutable() > $options['expiresAt']) { diff --git a/src/functions.php b/src/functions.php index 23bb6d1a..81153184 100644 --- a/src/functions.php +++ b/src/functions.php @@ -6,6 +6,14 @@ /** * @internal + * + * Creates a partially applied function by binding initial arguments to the given callable. + * + * Returns a Closure that, when invoked, calls the original callable with the bound arguments prepended + * to any new ones. + * + * Used internally to build reusable “waiter” functions (e.g., binding the HTTP client to + * task-waiting logic) and reduce repetitive argument passing. */ function partial(callable $func, ...$boundArgs): \Closure { diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 4d0f50de..1d4e34e9 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -23,7 +23,7 @@ final class DocumentsTest extends TestCase public function testAddDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS)->wait(); + $index->addDocuments(self::DOCUMENTS)->wait(); $response = $index->getDocuments(); self::assertCount(\count(self::DOCUMENTS), $response); @@ -53,7 +53,7 @@ public function testAddDocumentWithSpecialChars(): void ]; $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments($documents)->wait(); + $index->addDocuments($documents)->wait(); $response = $index->getDocuments(); self::assertCount(\count($documents), $response); @@ -203,14 +203,14 @@ public function testReplaceDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS)->wait(); + $index->addDocuments(self::DOCUMENTS)->wait(); $replacement = [ 'id' => 2, 'title' => 'The Red And The Black', ]; - $task = $index->addDocuments([$replacement])->wait(); + $index->addDocuments([$replacement])->wait(); $response = $index->getDocument($replacement['id']); @@ -283,7 +283,7 @@ public function testUpdateDocumentsByFunction(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS)->wait(); + $index->addDocuments(self::DOCUMENTS)->wait(); $function = ' if doc.id % context.modulo == 0 { @@ -412,14 +412,14 @@ public function testAddWithUpdateDocuments(): void { $index = $this->createEmptyIndex($this->safeIndexName('movies')); - $task = $index->addDocuments(self::DOCUMENTS)->wait(); + $index->addDocuments(self::DOCUMENTS)->wait(); $document = [ 'id' => 9, 'title' => '1984', ]; - $task = $index->updateDocuments([$document])->wait(); + $index->updateDocuments([$document])->wait(); $response = $index->getDocument($document['id']); diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index 3e3a7946..f12bb8cb 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -190,7 +190,6 @@ public function testWaitForTaskDefault(): void $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(); self::assertSame(TaskStatus::Succeeded, $task->getStatus()); - self::assertSame($task->getTaskUid(), $task->getTaskUid()); self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); self::assertNotNull($task->getDuration()); self::assertNotNull($task->getStartedAt()); @@ -202,7 +201,6 @@ public function testWaitForTaskWithTimeoutAndInterval(): void $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(750, 20); self::assertSame(TaskStatus::Succeeded, $task->getStatus()); - self::assertSame($task->getTaskUid(), $task->getTaskUid()); self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); self::assertNotNull($task->getDuration()); self::assertNotNull($task->getStartedAt()); @@ -214,7 +212,6 @@ public function testWaitForTaskWithTimeout(): void $task = $this->index->addDocuments([['id' => 1, 'title' => 'Pride and Prejudice']])->wait(1000); self::assertSame(TaskStatus::Succeeded, $task->getStatus()); - self::assertSame($task->getTaskUid(), $task->getTaskUid()); self::assertSame(TaskType::DocumentAdditionOrUpdate, $task->getType()); self::assertNotNull($task->getDuration()); self::assertNotNull($task->getStartedAt()); diff --git a/tests/Endpoints/SearchTest.php b/tests/Endpoints/SearchTest.php index 3d7b0428..800e40ca 100644 --- a/tests/Endpoints/SearchTest.php +++ b/tests/Endpoints/SearchTest.php @@ -490,7 +490,7 @@ public function testSearchSortWithString(): void public function testSearchSortWithInt(): void { - $task = $this->index->updateRankingRules([ + $this->index->updateRankingRules([ 'words', 'typo', 'sort', From 12574f2adfd8ec90614383dbf3b55c39ea89bc95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:43:36 +0200 Subject: [PATCH 43/51] Fix test --- tests/Endpoints/IndexTest.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/Endpoints/IndexTest.php b/tests/Endpoints/IndexTest.php index f12bb8cb..17af9548 100644 --- a/tests/Endpoints/IndexTest.php +++ b/tests/Endpoints/IndexTest.php @@ -246,13 +246,12 @@ public function testDeleteIndexes(): void public function testSwapIndexes(): void { $task = $this->client->swapIndexes([['indexA', 'indexB'], ['indexC', 'indexD']])->wait(); + self::assertInstanceOf(IndexSwapDetails::class, $details = $task->getDetails()); - self::assertSame(['indexA', 'indexB'], $response['details']['swaps'][0]['indexes']); - self::assertSame(['indexC', 'indexD'], $response['details']['swaps'][1]['indexes']); - self::assertFalse($response['details']['swaps'][0]['rename']); - self::assertFalse($response['details']['swaps'][1]['rename']); -// self::assertInstanceOf(IndexSwapDetails::class, $details = $task->getDetails()); -// self::assertSame([['indexes' => ['indexA', 'indexB']], ['indexes' => ['indexC', 'indexD']]], $details->swaps); + self::assertSame(['indexA', 'indexB'], $details->swaps[0]['indexes']); + self::assertSame(['indexC', 'indexD'], $details->swaps[1]['indexes']); + self::assertFalse($details->swaps[0]['rename']); + self::assertFalse($details->swaps[1]['rename']); } public function testDeleteTasks(): void From c0e77e205cd19279658554cbc110a289a44cf24a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:45:58 +0200 Subject: [PATCH 44/51] Remove dropped php versions from gh workflows --- .github/workflows/meilisearch-beta-tests.yml | 2 +- .github/workflows/pre-release-tests.yml | 2 +- .github/workflows/tests.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/meilisearch-beta-tests.yml b/.github/workflows/meilisearch-beta-tests.yml index 728c361e..86920753 100644 --- a/.github/workflows/meilisearch-beta-tests.yml +++ b/.github/workflows/meilisearch-beta-tests.yml @@ -40,7 +40,7 @@ jobs: MEILI_NO_ANALYTICS: true strategy: matrix: - php-version: ["7.4", "8.0", "8.1", "8.2", "8.3", "8.4"] + php-version: ["8.1", "8.2", "8.3", "8.4"] steps: - name: Checkout code diff --git a/.github/workflows/pre-release-tests.yml b/.github/workflows/pre-release-tests.yml index 09cc1978..552ed123 100644 --- a/.github/workflows/pre-release-tests.yml +++ b/.github/workflows/pre-release-tests.yml @@ -40,7 +40,7 @@ jobs: MEILI_NO_ANALYTICS: true strategy: matrix: - php-version: ["7.4", "8.0", "8.1", "8.2", "8.3", "8.4"] + php-version: ["8.1", "8.2", "8.3", "8.4"] steps: - name: Checkout code diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 132e346d..839903a8 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -77,7 +77,7 @@ jobs: MEILI_NO_ANALYTICS: true strategy: matrix: - php-version: ['7.4', '8.0', '8.1', '8.2', '8.3', '8.4'] + php-version: ['8.1', '8.2', '8.3', '8.4'] steps: - uses: actions/checkout@v5 From 288f6c5e7a4382432dbd8532eb8c35344806a6e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:47:27 +0200 Subject: [PATCH 45/51] Fix coderabbit comment --- src/Http/Serialize/Json.php | 2 +- src/Http/Serialize/SerializerInterface.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Http/Serialize/Json.php b/src/Http/Serialize/Json.php index 8bf9f56a..ea35590d 100644 --- a/src/Http/Serialize/Json.php +++ b/src/Http/Serialize/Json.php @@ -11,7 +11,7 @@ public function serialize(mixed $data): string return json_encode($data, JSON_THROW_ON_ERROR); } - public function unserialize(mixed $string): mixed + public function unserialize(string $string): mixed { return json_decode($string, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR); } diff --git a/src/Http/Serialize/SerializerInterface.php b/src/Http/Serialize/SerializerInterface.php index 941f25e6..9c5fdb22 100644 --- a/src/Http/Serialize/SerializerInterface.php +++ b/src/Http/Serialize/SerializerInterface.php @@ -22,5 +22,5 @@ public function serialize(mixed $data): string; * * @throws \JsonException */ - public function unserialize(mixed $string): mixed; + public function unserialize(string $string): mixed; } From 6f61cea31d102cd6ede136aa9412f954a0b3d0f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:54:16 +0200 Subject: [PATCH 46/51] Fix failing tests --- src/Contracts/TaskDetails/IndexSwapDetails.php | 4 ++-- tests/Endpoints/DocumentsTest.php | 6 ++---- tests/Endpoints/MultiModalSearchTest.php | 8 +++----- tests/Settings/ChatTest.php | 5 +---- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/Contracts/TaskDetails/IndexSwapDetails.php b/src/Contracts/TaskDetails/IndexSwapDetails.php index 56493685..5de59b5d 100644 --- a/src/Contracts/TaskDetails/IndexSwapDetails.php +++ b/src/Contracts/TaskDetails/IndexSwapDetails.php @@ -8,13 +8,13 @@ /** * @implements TaskDetails + * swaps: array * }> */ final class IndexSwapDetails implements TaskDetails { /** - * @param array $swaps + * @param array $swaps */ public function __construct( public readonly array $swaps, diff --git a/tests/Endpoints/DocumentsTest.php b/tests/Endpoints/DocumentsTest.php index 1d4e34e9..163195ac 100644 --- a/tests/Endpoints/DocumentsTest.php +++ b/tests/Endpoints/DocumentsTest.php @@ -628,8 +628,7 @@ public function testGetDocumentsWithSort(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $index->updateSortableAttributes(['id', 'genre']); $index->updateFilterableAttributes(['id', 'genre']); - $promise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($promise['taskUid']); + $index->addDocuments(self::DOCUMENTS)->wait(); $response = $index->getDocuments((new DocumentsQuery())->setSort(['genre:desc', 'id:asc'])); self::assertSame(2, $response[0]['id']); @@ -643,8 +642,7 @@ public function testGetDocumentsWithFiltersFieldsAndSort(): void $index = $this->createEmptyIndex($this->safeIndexName('movies')); $index->updateSortableAttributes(['id', 'genre']); $index->updateFilterableAttributes(['id', 'genre']); - $promise = $index->addDocuments(self::DOCUMENTS); - $index->waitForTask($promise['taskUid']); + $index->addDocuments(self::DOCUMENTS)->wait(); $query = (new DocumentsQuery()) ->setSort(['genre:desc', 'id:asc']) diff --git a/tests/Endpoints/MultiModalSearchTest.php b/tests/Endpoints/MultiModalSearchTest.php index 0e7d329d..128e3218 100644 --- a/tests/Endpoints/MultiModalSearchTest.php +++ b/tests/Endpoints/MultiModalSearchTest.php @@ -26,19 +26,17 @@ protected function setUp(): void } $this->index = $this->createEmptyIndex($this->safeIndexName()); - $updateSettingsPromise = $this->index->updateSettings([ + $this->index->updateSettings([ 'searchableAttributes' => ['title', 'overview'], 'embedders' => [ 'multimodal' => self::getVoyageEmbedderConfig($voyageApiKey), ], - ]); - $this->index->waitForTask($updateSettingsPromise['taskUid']); + ])->wait(); // Load the movies.json dataset $documentsJson = file_get_contents('./tests/datasets/movies.json'); $this->documents = json_decode($documentsJson, true, 512, JSON_THROW_ON_ERROR); - $addDocumentsPromise = $this->index->addDocuments($this->documents); - $this->index->waitForTask($addDocumentsPromise['taskUid']); + $this->index->addDocuments($this->documents)->wait(); } public function testTextOnlySearch(): void diff --git a/tests/Settings/ChatTest.php b/tests/Settings/ChatTest.php index 9b478f3b..ccb493d2 100644 --- a/tests/Settings/ChatTest.php +++ b/tests/Settings/ChatTest.php @@ -54,10 +54,7 @@ public function testUpdateChatSettings(): void ], ]; - $promise = $this->index->updateChat($newSettings); - - $this->assertIsValidPromise($promise); - $this->index->waitForTask($promise['taskUid']); + $this->index->updateChat($newSettings)->wait(); $settings = $this->index->getChat(); self::assertSame($newSettings['description'], $settings['description']); From 33c2781fb2ddb6c4b4d179b6919e5b63f60f27b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:56:04 +0200 Subject: [PATCH 47/51] Pass waiter fn --- src/Endpoints/Delegates/HandlesSettings.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Endpoints/Delegates/HandlesSettings.php b/src/Endpoints/Delegates/HandlesSettings.php index 4f80b531..d6f1bca9 100644 --- a/src/Endpoints/Delegates/HandlesSettings.php +++ b/src/Endpoints/Delegates/HandlesSettings.php @@ -595,6 +595,6 @@ public function getChat(): array */ public function updateChat(array $chatSettings): Task { - return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/chat', $chatSettings)); + return Task::fromArray($this->http->patch(self::PATH.'/'.$this->uid.'/settings/chat', $chatSettings), partial(Tasks::waitTask(...), $this->http)); } } From 93512cd1013c27674ec3d903d8763055d63fe312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:57:55 +0200 Subject: [PATCH 48/51] Add missing type --- src/Contracts/Http.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Contracts/Http.php b/src/Contracts/Http.php index 812c2809..23b60975 100644 --- a/src/Contracts/Http.php +++ b/src/Contracts/Http.php @@ -47,5 +47,5 @@ public function delete(string $path, array $query = []); * @throws ApiException * @throws \JsonException */ - public function postStream(string $path, $body = null, array $query = []): StreamInterface; + public function postStream(string $path, mixed $body = null, array $query = []): StreamInterface; } From 4b361f1c139fbc1436694833932ddbb6b88f3f60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 08:58:37 +0200 Subject: [PATCH 49/51] Add missing types --- src/Http/Client.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Http/Client.php b/src/Http/Client.php index 243016cb..32d3141b 100644 --- a/src/Http/Client.php +++ b/src/Http/Client.php @@ -84,7 +84,7 @@ public function get(string $path, array $query = []) * @throws CommunicationException * @throws \JsonException */ - public function post(string $path, $body = null, array $query = [], ?string $contentType = null) + public function post(string $path, mixed $body = null, array $query = [], ?string $contentType = null) { if (null === $contentType) { $body = $this->json->serialize($body); @@ -105,7 +105,7 @@ public function post(string $path, $body = null, array $query = [], ?string $con * @throws CommunicationException * @throws \JsonException */ - public function put(string $path, $body = null, array $query = [], ?string $contentType = null) + public function put(string $path, mixed $body = null, array $query = [], ?string $contentType = null) { if (null === $contentType) { $body = $this->json->serialize($body); @@ -118,7 +118,7 @@ public function put(string $path, $body = null, array $query = [], ?string $cont return $this->execute($request, ['Content-type' => $contentType ?? 'application/json']); } - public function patch(string $path, $body = null, array $query = []) + public function patch(string $path, mixed $body = null, array $query = []) { $request = $this->requestFactory->createRequest( 'PATCH', @@ -144,7 +144,7 @@ public function delete(string $path, array $query = []) * @throws CommunicationException * @throws \JsonException */ - public function postStream(string $path, $body = null, array $query = []): StreamInterface + public function postStream(string $path, mixed $body = null, array $query = []): StreamInterface { $request = $this->requestFactory->createRequest( 'POST', From a01eab9bcdb360601dd079d2107877f41305a9d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 09:06:14 +0200 Subject: [PATCH 50/51] Add `UnknownTaskDetails`, `TaskType::Unknown`, `TaskStatus::Unknown` --- src/Contracts/Task.php | 7 +++-- .../TaskDetails/UnknownTaskDetails.php | 26 +++++++++++++++++++ src/Contracts/TaskStatus.php | 1 + src/Contracts/TaskType.php | 1 + 4 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/Contracts/TaskDetails/UnknownTaskDetails.php diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index f69babdd..40ce5975 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -15,6 +15,7 @@ use Meilisearch\Contracts\TaskDetails\SettingsUpdateDetails; use Meilisearch\Contracts\TaskDetails\TaskCancelationDetails; use Meilisearch\Contracts\TaskDetails\TaskDeletionDetails; +use Meilisearch\Contracts\TaskDetails\UnknownTaskDetails; use Meilisearch\Exceptions\LogicException; final class Task @@ -150,12 +151,13 @@ public function wait(int $timeoutInMs = 5000, int $intervalInMs = 50): Task public static function fromArray(array $data, ?\Closure $await = null): Task { $details = $data['details'] ?? null; + $type = TaskType::tryFrom($data['type']) ?? TaskType::Unknown; return new self( $data['taskUid'] ?? $data['uid'], $data['indexUid'] ?? null, - TaskStatus::from($data['status']), - $type = TaskType::from($data['type']), + TaskStatus::tryFrom($data['status']) ?? TaskStatus::Unknown, + $type, new \DateTimeImmutable($data['enqueuedAt']), \array_key_exists('startedAt', $data) && null !== $data['startedAt'] ? new \DateTimeImmutable($data['startedAt']) : null, \array_key_exists('finishedAt', $data) && null !== $data['finishedAt'] ? new \DateTimeImmutable($data['finishedAt']) : null, @@ -177,6 +179,7 @@ public static function fromArray(array $data, ?\Closure $await = null): Task // It’s intentional that SnapshotCreation tasks don’t have a details object // (no SnapshotCreationDetails exists and tests don’t exercise any details) TaskType::SnapshotCreation => null, + TaskType::Unknown => UnknownTaskDetails::fromArray($details), }, \array_key_exists('error', $data) && null !== $data['error'] ? TaskError::fromArray($data['error']) : null, $await, diff --git a/src/Contracts/TaskDetails/UnknownTaskDetails.php b/src/Contracts/TaskDetails/UnknownTaskDetails.php new file mode 100644 index 00000000..b499b07d --- /dev/null +++ b/src/Contracts/TaskDetails/UnknownTaskDetails.php @@ -0,0 +1,26 @@ + + */ +final class UnknownTaskDetails implements TaskDetails +{ + /** + * @param array $data + */ + public function __construct( + public readonly array $data, + ) { + } + + public static function fromArray(array $data): self + { + return new self($data); + } +} diff --git a/src/Contracts/TaskStatus.php b/src/Contracts/TaskStatus.php index 6ca36a7f..03e665e3 100644 --- a/src/Contracts/TaskStatus.php +++ b/src/Contracts/TaskStatus.php @@ -11,4 +11,5 @@ enum TaskStatus: string case Failed = 'failed'; case Succeeded = 'succeeded'; case Processing = 'processing'; + case Unknown = 'unknown'; } diff --git a/src/Contracts/TaskType.php b/src/Contracts/TaskType.php index 198d9a07..d02088ac 100644 --- a/src/Contracts/TaskType.php +++ b/src/Contracts/TaskType.php @@ -18,4 +18,5 @@ enum TaskType: string case TaskCancelation = 'taskCancelation'; case TaskDeletion = 'taskDeletion'; case SnapshotCreation = 'snapshotCreation'; + case Unknown = 'unknown'; } From 92756796e7596e2bba768cbb1ff40eb715a60463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomas=20Nork=C5=ABnas?= Date: Mon, 17 Nov 2025 15:49:24 +0200 Subject: [PATCH 51/51] Fix passing no details --- src/Contracts/Task.php | 2 +- src/Contracts/TaskDetails/UnknownTaskDetails.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Contracts/Task.php b/src/Contracts/Task.php index 40ce5975..ab548516 100644 --- a/src/Contracts/Task.php +++ b/src/Contracts/Task.php @@ -179,7 +179,7 @@ public static function fromArray(array $data, ?\Closure $await = null): Task // It’s intentional that SnapshotCreation tasks don’t have a details object // (no SnapshotCreationDetails exists and tests don’t exercise any details) TaskType::SnapshotCreation => null, - TaskType::Unknown => UnknownTaskDetails::fromArray($details), + TaskType::Unknown => UnknownTaskDetails::fromArray($details ?? []), }, \array_key_exists('error', $data) && null !== $data['error'] ? TaskError::fromArray($data['error']) : null, $await, diff --git a/src/Contracts/TaskDetails/UnknownTaskDetails.php b/src/Contracts/TaskDetails/UnknownTaskDetails.php index b499b07d..f1a5b579 100644 --- a/src/Contracts/TaskDetails/UnknownTaskDetails.php +++ b/src/Contracts/TaskDetails/UnknownTaskDetails.php @@ -7,7 +7,7 @@ use Meilisearch\Contracts\TaskDetails; /** - * @implements TaskDetails + * @implements TaskDetails> */ final class UnknownTaskDetails implements TaskDetails {