koel/app/Services/SearchService.php

54 lines
1.7 KiB
PHP
Raw Normal View History

2020-12-24 12:41:18 +00:00
<?php
namespace App\Services;
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;
use Illuminate\Support\Collection;
2020-12-24 12:41:18 +00:00
use Laravel\Scout\Builder;
class SearchService
{
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> */
public function excerptSearch(string $keywords, int $count): array
2020-12-24 12:41:18 +00:00
{
return [
'songs' => self::getTopResults($this->songRepository->search($keywords), $count)
2021-06-05 10:47:56 +00:00
->map(static fn (Song $song): string => $song->id),
'artists' => self::getTopResults($this->artistRepository->search($keywords), $count)
2021-06-05 10:47:56 +00:00
->map(static fn (Artist $artist): int => $artist->id),
'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> */
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
/** @return Collection|array<string> */
public function searchSongs(string $keywords): Collection
2020-12-24 22:35:39 +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
}