Files
ai-web/app/Http/Controllers/Site/NewsController.php

88 lines
3.1 KiB
PHP
Raw Permalink Normal View History

2026-02-11 17:28:36 +08:00
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Site;
use App\Http\Controllers\Controller;
use App\Models\AiModel;
use App\Models\Article;
use App\Models\Category;
use App\Models\Guide;
use App\Support\MarkdownRenderer;
use Illuminate\Contracts\View\View;
2026-02-12 10:31:53 +08:00
use Illuminate\Database\Eloquent\Builder;
2026-02-11 17:28:36 +08:00
use Illuminate\Http\Request;
class NewsController extends Controller
{
public function __construct(
private readonly MarkdownRenderer $markdownRenderer,
) {
}
public function index(Request $request): View
{
$builder = Article::query()->published()->with('category');
if ($request->filled('q')) {
$builder->whereFullText(['title', 'excerpt', 'body'], (string) $request->string('q'));
}
if ($request->filled('category')) {
$builder->whereHas('category', function ($query) use ($request): void {
$query->where('slug', (string) $request->string('category'));
});
}
2026-02-12 10:31:53 +08:00
$categories = Category::query()
->where('type', 'news')
->where('is_active', true)
->withCount([
'articles as published_articles_count' => fn (Builder $query): Builder => $query->published(),
])
->orderByDesc('published_articles_count')
->orderBy('name')
->get();
$newsStats = [
'total' => Article::query()->published()->count(),
'today' => Article::query()->published()->whereDate('published_at', today())->count(),
'high_source' => Article::query()->published()->where('source_level', 'high')->count(),
'updated_7d' => Article::query()->published()->where('updated_at', '>=', now()->subDays(7))->count(),
];
2026-02-11 17:28:36 +08:00
return view('public.news.index', [
'items' => $builder->latest('published_at')->paginate(15)->withQueryString(),
2026-02-12 10:31:53 +08:00
'categories' => $categories,
'newsStats' => $newsStats,
2026-02-11 17:28:36 +08:00
'filters' => $request->only(['q', 'category']),
'sidebarModels' => AiModel::published()->orderByDesc('total_score')->limit(6)->get(),
'sidebarGuides' => Guide::published()->latest('published_at')->limit(6)->get(),
]);
}
public function show(string $slug): View
{
/** @var Article $article */
$article = Article::query()
->published()
->with(['category', 'source'])
->where('slug', $slug)
->firstOrFail();
return view('public.news.show', [
'item' => $article,
'bodyHtml' => $this->markdownRenderer->render($article->body),
'showRiskNotice' => $this->containsRiskKeyword($article->title.' '.$article->body),
2026-02-12 10:31:53 +08:00
'sidebarModels' => AiModel::published()->orderByDesc('total_score')->limit(6)->get(),
'sidebarGuides' => Guide::published()->latest('published_at')->limit(6)->get(),
2026-02-11 17:28:36 +08:00
]);
}
private function containsRiskKeyword(string $text): bool
{
return str_contains($text, '医疗') || str_contains($text, '法律') || str_contains($text, '投资');
}
}