koel/app/Services/LibraryManager.php

45 lines
1.3 KiB
PHP
Raw Normal View History

2022-06-10 10:47:46 +00:00
<?php
namespace App\Services;
use App\Models\Album;
use App\Models\Artist;
use Illuminate\Support\Facades\DB;
class LibraryManager
{
/**
2024-02-24 15:37:01 +00:00
* Delete albums and artists that have no songs.
*
* @return array<mixed>
2022-06-10 10:47:46 +00:00
*/
public function prune(bool $dryRun = false): array
{
return DB::transaction(static function () use ($dryRun): array {
$albumQuery = Album::query()
->leftJoin('songs', 'songs.album_id', '=', 'albums.id')
2022-06-10 10:47:46 +00:00
->whereNull('songs.album_id')
->whereNotIn('albums.id', [Album::UNKNOWN_ID]);
$artistQuery = Artist::query()
->leftJoin('songs', 'songs.artist_id', '=', 'artists.id')
2022-06-10 10:47:46 +00:00
->leftJoin('albums', 'albums.artist_id', '=', 'artists.id')
->whereNull('songs.artist_id')
->whereNull('albums.artist_id')
->whereNotIn('artists.id', [Artist::UNKNOWN_ID, Artist::VARIOUS_ID]);
$results = [
'albums' => $albumQuery->get('albums.*'),
'artists' => $artistQuery->get('artists.*'),
];
if (!$dryRun) {
$albumQuery->delete();
$artistQuery->delete();
}
return $results;
});
}
}