jikan-rest/app/Services/ElasticScoutSearchService.php
pushrbx a145f18bbd wip - major refactor
- AppServiceProvider is needs more work to wire in new services
- todo: more dtos
- todo: add unit tests
- todo: add more integration tests
2023-05-21 11:14:34 +01:00

53 lines
2.1 KiB
PHP

<?php
namespace App\Services;
use App\Contracts\Repository;
use App\JikanApiSearchableModel;
use ONGR\ElasticsearchDSL\Sort\FieldSort;
class ElasticScoutSearchService implements ScoutSearchService
{
public function __construct(private readonly Repository $repository)
{
}
/**
* Executes a search operation via Laravel Scout on the provided model class.
* @param string $q
* @return \Laravel\Scout\Builder
* @throws \Elastic\Elasticsearch\Exception\ServerResponseException
* @throws \Elastic\Elasticsearch\Exception\ClientResponseException
* @throws \Elastic\Elasticsearch\Exception\MissingParameterException
*/
public function search(string $q, ?string $orderByField = null,
bool $sortDirectionDescending = false): \Laravel\Scout\Builder
{
return $this->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()]);
});
}
}