koel/app/Repositories/GenreRepository.php

48 lines
1.6 KiB
PHP
Raw Normal View History

2022-10-21 20:06:43 +00:00
<?php
namespace App\Repositories;
use App\Models\Song;
2024-01-03 17:02:18 +00:00
use App\Models\User;
2022-10-21 20:06:43 +00:00
use App\Values\Genre;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class GenreRepository
{
/** @return Collection|array<array-key, Genre> */
2024-01-03 17:02:18 +00:00
public function getAll(?User $scopedUser = null): Collection
2022-10-21 20:06:43 +00:00
{
return Song::query()
2024-01-03 17:02:18 +00:00
->accessibleBy($scopedUser ?? auth()->user())
2022-10-21 20:06:43 +00:00
->select('genre', DB::raw('COUNT(id) AS song_count'), DB::raw('SUM(length) AS length'))
->groupBy('genre')
->orderBy('genre')
->get()
->transform(static fn (object $record): Genre => Genre::make( // @phpstan-ignore-line
name: $record->genre ?: Genre::NO_GENRE, // @phpstan-ignore-line
songCount: $record->song_count, // @phpstan-ignore-line
length: $record->length // @phpstan-ignore-line
2022-10-21 20:06:43 +00:00
));
}
2024-01-03 17:02:18 +00:00
public function getOne(string $name, ?User $scopedUser = null): ?Genre
2022-10-21 20:06:43 +00:00
{
/** @var object|null $record */
$record = Song::query()
2024-01-03 17:02:18 +00:00
->accessibleBy($scopedUser ?? auth()->user())
2022-10-21 20:06:43 +00:00
->select('genre', DB::raw('COUNT(id) AS song_count'), DB::raw('SUM(length) AS length'))
->groupBy('genre')
->where('genre', $name === Genre::NO_GENRE ? '' : $name)
->first();
return $record
? Genre::make(
name: $record->genre ?: Genre::NO_GENRE,
songCount: $record->song_count,
length: $record->length
)
: null;
}
}