31 lines
921 B
PHP
31 lines
921 B
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Category;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class ArticleSelector
|
|
{
|
|
public function forCategory(Category $category, int $limit = 10): Collection
|
|
{
|
|
$feeds = $category->feeds()->with([
|
|
'articles' => fn ($q) => $q->orderByDesc('published_at')->limit($limit),
|
|
])->get();
|
|
|
|
// Round robin: take article[0] from every feed, then article[1] from every feed, etc.
|
|
$buckets = $feeds->map(fn ($feed) => $feed->articles->values());
|
|
$maxDepth = $buckets->max(fn ($b) => $b->count()) ?? 0;
|
|
|
|
$selected = collect();
|
|
for ($i = 0; $i < $maxDepth && $selected->count() < $limit; $i++) {
|
|
foreach ($buckets as $bucket) {
|
|
if ($selected->count() >= $limit) break;
|
|
if ($bucket->has($i)) $selected->push($bucket[$i]);
|
|
}
|
|
}
|
|
|
|
return $selected;
|
|
}
|
|
}
|