2022-06-18 15:03:50 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2023-01-02 16:29:05 +00:00
|
|
|
use App\Contracts\Repository;
|
2022-06-18 15:03:50 +01:00
|
|
|
use App\JikanApiSearchableModel;
|
|
|
|
use ONGR\ElasticsearchDSL\Sort\FieldSort;
|
|
|
|
|
|
|
|
class ElasticScoutSearchService implements ScoutSearchService
|
|
|
|
{
|
2023-01-02 16:29:05 +00:00
|
|
|
public function __construct(private readonly Repository $repository)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2022-06-18 15:03:50 +01:00
|
|
|
/**
|
|
|
|
* 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
|
|
|
|
*/
|
2023-01-02 16:29:05 +00:00
|
|
|
public function search(string $q, ?string $orderByField = null,
|
2022-12-22 15:45:54 +00:00
|
|
|
bool $sortDirectionDescending = false): \Laravel\Scout\Builder
|
2022-06-18 15:03:50 +01:00
|
|
|
{
|
2023-01-02 16:29:05 +00:00
|
|
|
return $this->repository->search($q, function(\Elastic\ElasticSearch\Client $client, \ONGR\ElasticsearchDSL\Search $body) use ($orderByField, $sortDirectionDescending) {
|
|
|
|
$modelInstance = $this->repository->createEntity();
|
2022-06-18 15:03:50 +01:00
|
|
|
|
|
|
|
if ($modelInstance instanceof JikanApiSearchableModel) {
|
2022-12-22 15:45:54 +00:00
|
|
|
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,
|
|
|
|
};
|
2022-06-18 15:03:50 +01:00
|
|
|
|
2022-12-22 15:45:54 +00:00
|
|
|
$sort = new FieldSort($f['field'], ['order' => $direction]);
|
|
|
|
$body->addSort($sort);
|
|
|
|
}
|
2022-06-18 15:03:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $client->search(['index' => $modelInstance->searchableAs(), 'body' => $body->toArray()]);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|