2020-12-24 12:41:18 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2020-12-25 11:52:28 +00:00
|
|
|
use App\Models\Album;
|
|
|
|
use App\Models\Artist;
|
|
|
|
use App\Models\Song;
|
2020-12-24 12:41:18 +00:00
|
|
|
use App\Repositories\AlbumRepository;
|
|
|
|
use App\Repositories\ArtistRepository;
|
|
|
|
use App\Repositories\SongRepository;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
2020-12-25 11:52:28 +00:00
|
|
|
use Illuminate\Support\Collection;
|
2020-12-24 12:41:18 +00:00
|
|
|
use Laravel\Scout\Builder;
|
|
|
|
|
|
|
|
class SearchService
|
|
|
|
{
|
2020-12-25 11:52:28 +00:00
|
|
|
public const DEFAULT_EXCERPT_RESULT_COUNT = 6;
|
|
|
|
|
2020-12-24 12:41:18 +00:00
|
|
|
public function __construct(
|
2022-07-29 06:47:10 +00:00
|
|
|
private SongRepository $songRepository,
|
|
|
|
private AlbumRepository $albumRepository,
|
|
|
|
private ArtistRepository $artistRepository
|
2020-12-24 12:41:18 +00:00
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @return array<mixed> */
|
2020-12-25 11:52:28 +00:00
|
|
|
public function excerptSearch(string $keywords, int $count): array
|
2020-12-24 12:41:18 +00:00
|
|
|
{
|
|
|
|
return [
|
2020-12-25 11:52:28 +00:00
|
|
|
'songs' => self::getTopResults($this->songRepository->search($keywords), $count)
|
2021-06-05 10:47:56 +00:00
|
|
|
->map(static fn (Song $song): string => $song->id),
|
2020-12-25 11:52:28 +00:00
|
|
|
'artists' => self::getTopResults($this->artistRepository->search($keywords), $count)
|
2021-06-05 10:47:56 +00:00
|
|
|
->map(static fn (Artist $artist): int => $artist->id),
|
2020-12-25 11:52:28 +00:00
|
|
|
'albums' => self::getTopResults($this->albumRepository->search($keywords), $count)
|
2021-06-05 10:47:56 +00:00
|
|
|
->map(static fn (Album $album): int => $album->id),
|
2020-12-24 12:41:18 +00:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @return Collection|array<Model> */
|
2020-12-25 11:52:28 +00:00
|
|
|
private static function getTopResults(Builder $query, int $count): Collection
|
2020-12-24 12:41:18 +00:00
|
|
|
{
|
|
|
|
return $query->take($count)->get();
|
|
|
|
}
|
2020-12-24 22:35:39 +00:00
|
|
|
|
2020-12-25 11:52:28 +00:00
|
|
|
/** @return Collection|array<string> */
|
|
|
|
public function searchSongs(string $keywords): Collection
|
2020-12-24 22:35:39 +00:00
|
|
|
{
|
2020-12-25 11:52:28 +00:00
|
|
|
return $this->songRepository
|
|
|
|
->search($keywords)
|
|
|
|
->get()
|
2022-07-27 15:32:36 +00:00
|
|
|
->map(static fn (Song $song): string => $song->id); // @phpstan-ignore-line
|
2020-12-24 22:35:39 +00:00
|
|
|
}
|
2020-12-24 12:41:18 +00:00
|
|
|
}
|