koel/app/Services/SearchService.php

59 lines
1.8 KiB
PHP
Raw Normal View History

2020-12-24 13:41:18 +01:00
<?php
namespace App\Services;
2023-06-05 23:46:41 +02:00
use App\Builders\SongBuilder;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
2023-06-05 23:46:41 +02:00
use App\Models\User;
2020-12-24 13:41:18 +01:00
use App\Repositories\AlbumRepository;
use App\Repositories\ArtistRepository;
use App\Repositories\SongRepository;
2023-06-05 23:46:41 +02:00
use App\Values\ExcerptSearchResult;
use Illuminate\Support\Collection;
2020-12-24 13:41:18 +01:00
class SearchService
{
public const DEFAULT_EXCERPT_RESULT_COUNT = 6;
2023-06-05 23:46:41 +02:00
public const DEFAULT_MAX_SONG_RESULT_COUNT = 500;
2020-12-24 13:41:18 +01:00
public function __construct(
2022-07-29 08:47:10 +02:00
private SongRepository $songRepository,
private AlbumRepository $albumRepository,
private ArtistRepository $artistRepository
2020-12-24 13:41:18 +01:00
) {
}
2023-06-05 23:46:41 +02:00
public function excerptSearch(
string $keywords,
?User $scopedUser = null,
int $count = self::DEFAULT_EXCERPT_RESULT_COUNT
): ExcerptSearchResult {
$scopedUser ??= auth()->user();
2020-12-24 13:41:18 +01:00
2023-06-05 23:46:41 +02:00
return ExcerptSearchResult::make(
$this->songRepository->getByIds(
ids: Song::search($keywords)->get()->take($count)->pluck('id')->all(),
inThatOrder: true,
scopedUser: $scopedUser
2023-06-05 23:46:41 +02:00
),
$this->artistRepository->getByIds(Artist::search($keywords)->get()->take($count)->pluck('id')->all(), true),
$this->albumRepository->getByIds(Album::search($keywords)->get()->take($count)->pluck('id')->all(), true),
2023-06-05 23:46:41 +02:00
);
2020-12-24 13:41:18 +01:00
}
2020-12-24 23:35:39 +01:00
2023-06-05 23:46:41 +02:00
/** @return Collection|array<array-key, Song> */
public function searchSongs(
string $keywords,
?User $scopedUser = null,
int $limit = self::DEFAULT_MAX_SONG_RESULT_COUNT
): Collection {
return Song::search($keywords)
->query(static function (SongBuilder $builder) use ($scopedUser, $limit): void {
$builder->withMeta($scopedUser ?? auth()->user())->limit($limit);
})
->get();
2020-12-24 23:35:39 +01:00
}
2020-12-24 13:41:18 +01:00
}