koel/app/Repositories/ArtistRepository.php

72 lines
2.3 KiB
PHP
Raw Normal View History

2018-08-29 06:30:39 +00:00
<?php
namespace App\Repositories;
use App\Builders\ArtistBuilder;
2024-01-03 17:02:18 +00:00
use App\Facades\License;
2022-06-10 10:47:46 +00:00
use App\Models\Artist;
use App\Models\User;
use Illuminate\Contracts\Pagination\Paginator;
2022-06-10 10:47:46 +00:00
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection as BaseCollection;
2018-08-29 06:30:39 +00:00
2024-04-24 21:58:19 +00:00
/** @extends Repository<Artist> */
2022-07-29 06:47:10 +00:00
class ArtistRepository extends Repository
2018-08-29 06:30:39 +00:00
{
2022-06-10 10:47:46 +00:00
/** @return Collection|array<array-key, Artist> */
public function getMostPlayed(int $count = 6, ?User $user = null): Collection
{
$user ??= auth()->user();
return Artist::query()
2024-01-03 17:02:18 +00:00
->isStandard()
->accessibleBy($user)
->unless(
License::isPlus(), // if the license is Plus, accessibleBy() would have already joined with `songs`
static fn (ArtistBuilder $query) => $query->leftJoin('songs', 'artists.id', 'songs.artist_id')
)
->join('interactions', static function (JoinClause $join) use ($user): void {
$join->on('interactions.song_id', '=', 'songs.id')->where('interactions.user_id', $user->id);
})
2022-12-02 23:34:51 +00:00
->groupBy([
'artists.id',
'play_count',
'artists.name',
'artists.image',
'artists.created_at',
'artists.updated_at',
])
2024-01-03 17:02:18 +00:00
->distinct()
2022-06-10 10:47:46 +00:00
->orderByDesc('play_count')
->limit($count)
->get('artists.*');
2022-06-10 10:47:46 +00:00
}
/** @return Collection|array<array-key, Artist> */
public function getMany(array $ids, bool $preserveOrder = false, ?User $user = null): Collection|BaseCollection
2022-06-10 10:47:46 +00:00
{
$artists = Artist::query()
2022-06-10 10:47:46 +00:00
->isStandard()
2024-01-03 17:02:18 +00:00
->accessibleBy($user ?? auth()->user())
->whereIn('artists.id', $ids)
->groupBy('artists.id')
->distinct()
->get('artists.*');
return $preserveOrder ? $artists->orderByArray($ids) : $artists;
}
2024-01-03 17:02:18 +00:00
public function paginate(?User $user = null): Paginator
{
return Artist::query()
->isStandard()
2024-01-03 17:02:18 +00:00
->accessibleBy($user ?? auth()->user())
->groupBy('artists.id')
->distinct()
->orderBy('artists.name')
->select('artists.*')
->simplePaginate(21);
}
2018-08-29 06:30:39 +00:00
}