Files
dredgenews/app/Services/ArticleSelector.php
T
dredgy 439139a057
linter / quality (push) Has been cancelled
tests / ci (8.3) (push) Has been cancelled
tests / ci (8.4) (push) Has been cancelled
tests / ci (8.5) (push) Has been cancelled
Done
2026-07-04 23:09:00 +10:00

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;
}
}