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
|
|
|
private $songRepository;
|
|
|
|
private $albumRepository;
|
|
|
|
private $artistRepository;
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
SongRepository $songRepository,
|
|
|
|
AlbumRepository $albumRepository,
|
|
|
|
ArtistRepository $artistRepository
|
|
|
|
) {
|
|
|
|
$this->songRepository = $songRepository;
|
|
|
|
$this->albumRepository = $albumRepository;
|
|
|
|
$this->artistRepository = $artistRepository;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @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)
|
|
|
|
->map(static function (Song $song): string {
|
|
|
|
return $song->id;
|
|
|
|
}),
|
|
|
|
'artists' => self::getTopResults($this->artistRepository->search($keywords), $count)
|
|
|
|
->map(static function (Artist $artist): int {
|
|
|
|
return $artist->id;
|
|
|
|
}),
|
|
|
|
'albums' => self::getTopResults($this->albumRepository->search($keywords), $count)
|
|
|
|
->map(static function (Album $album): int {
|
|
|
|
return $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()
|
|
|
|
->map(static function (Song $song): string {
|
|
|
|
return $song->id;
|
|
|
|
});
|
2020-12-24 22:35:39 +00:00
|
|
|
}
|
2020-12-24 12:41:18 +00:00
|
|
|
}
|