2018-11-03 23:25:08 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2021-10-08 16:23:45 +00:00
|
|
|
use App\Exceptions\NonSmartPlaylistException;
|
2018-11-03 23:25:08 +00:00
|
|
|
use App\Models\Playlist;
|
|
|
|
use App\Models\Song;
|
2022-08-01 11:03:58 +00:00
|
|
|
use App\Models\User;
|
2021-10-08 16:23:45 +00:00
|
|
|
use App\Values\SmartPlaylistRule;
|
|
|
|
use App\Values\SmartPlaylistRuleGroup;
|
2018-11-03 23:25:08 +00:00
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
2021-10-08 16:23:45 +00:00
|
|
|
use Illuminate\Support\Collection;
|
2018-11-03 23:25:08 +00:00
|
|
|
|
|
|
|
class SmartPlaylistService
|
|
|
|
{
|
2022-07-06 11:05:21 +00:00
|
|
|
/** @return Collection|array<array-key, Song> */
|
2022-08-01 11:03:58 +00:00
|
|
|
public function getSongs(Playlist $playlist, ?User $user = null): Collection
|
2018-11-03 23:25:08 +00:00
|
|
|
{
|
2021-10-08 16:23:45 +00:00
|
|
|
throw_unless($playlist->is_smart, NonSmartPlaylistException::create($playlist));
|
2018-11-03 23:25:08 +00:00
|
|
|
|
2022-10-11 15:28:43 +00:00
|
|
|
$query = Song::query()->withMeta($user ?? $playlist->user);
|
2018-11-03 23:25:08 +00:00
|
|
|
|
2022-07-06 11:05:21 +00:00
|
|
|
$playlist->rule_groups->each(static function (SmartPlaylistRuleGroup $group, int $index) use ($query): void {
|
|
|
|
$clause = $index === 0 ? 'where' : 'orWhere';
|
2018-11-03 23:25:08 +00:00
|
|
|
|
2022-07-06 11:05:21 +00:00
|
|
|
$query->$clause(static function (Builder $subQuery) use ($group): void {
|
|
|
|
$group->rules->each(static function (SmartPlaylistRule $rule) use ($subQuery): void {
|
|
|
|
$subWhere = $rule->operator === SmartPlaylistRule::OPERATOR_IS_BETWEEN ? 'whereBetween' : 'where';
|
|
|
|
$subQuery->$subWhere(...$rule->toCriteriaParameters());
|
2021-10-08 16:23:45 +00:00
|
|
|
});
|
2018-11-18 21:50:03 +00:00
|
|
|
});
|
2018-11-03 23:25:08 +00:00
|
|
|
});
|
2018-11-18 21:50:03 +00:00
|
|
|
|
2022-07-06 11:05:21 +00:00
|
|
|
return $query->orderBy('songs.title')->get();
|
2018-11-03 23:25:08 +00:00
|
|
|
}
|
|
|
|
}
|