repository->search($q, function(\Elastic\ElasticSearch\Client $client, \ONGR\ElasticsearchDSL\Search $body) use ($orderByField, $sortDirectionDescending) { $modelInstance = $this->repository->createEntity(); if ($modelInstance instanceof JikanApiSearchableModel) { if (!is_null($orderByField)) { $body->addSort(new FieldSort($orderByField, ['order' => $sortDirectionDescending ? FieldSort::DESC : FieldSort::ASC])); } else { // if the model specifies search index sort order, use it $sortByFields = $modelInstance->getSearchIndexSortBy(); if (!is_null($sortByFields)) { foreach ($sortByFields as $f) { $direction = match ($f['direction']) { 'asc' => FieldSort::ASC, 'desc' => FieldSort::DESC, }; $sort = new FieldSort($f['field'], ['order' => $direction]); $body->addSort($sort); } } } } return $client->search(['index' => $modelInstance->searchableAs(), 'body' => $body->toArray()]); }); } }