Files
laralog/app/Blog/Controllers/PostController.php
T
goukiandCursor ae47447062
Build and Deploy / verify (push) Successful in 40s
Build and Deploy / deploy (push) Successful in 36s
feat: restore sablog browse modes and clean imported HTML
Keep the public site readable after import (nbsp, highlighter, wrapping code, compact pager) and finish the admin extras already in this tree: sticky levels, preview, page cache, and live llms.txt.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 21:33:02 +00:00

73 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Blog\Controllers;
use App\Blog\Services\PostContentRenderer;
use App\Models\Post;
use Illuminate\Pagination\Paginator;
class PostController extends Controller
{
public function __construct(private PostContentRenderer $renderer) {}
public function show(string $id, ?string $page = null)
{
$post = Post::query()
->where('id', (int) $id)
->orWhere('slug', $id)
->first();
abort_unless($post, 404);
$canPreview = $this->canPreviewUnpublished();
abort_unless($post->status === 'published' || $canPreview, 404);
$this->ensureReadable($post);
// sablog 式 /show-{id}-{page}.shtml 的评论分页
if ($page !== null) {
Paginator::currentPageResolver(fn () => max(1, (int) $page));
}
// 浏览量由 /track-view 端点统计(页面整页缓存下控制器不执行,避免双计)
$comments = $post->comments()
->where('status', 'published')
->orderBy('created_at', (int) blog_setting('comment_order', 1) === 1 ? 'asc' : 'desc')
->paginate(20);
$rendered = $this->renderer->renderWithToc($post);
return theme_view('show', [
'post' => $post,
'comments' => $comments,
'contentHtml' => $rendered['html'],
'toc' => $rendered['toc'],
'isPreview' => $post->status !== 'published' && $canPreview,
]);
}
private function canPreviewUnpublished(): bool
{
$user = auth()->user();
return $user && ($user->isAdmin() || $user->hasRole('editor'));
}
private function ensureReadable(Post $post): void
{
if (! $post->read_password) {
return;
}
$granted = session()->get("post_read_password.{$post->id}") === $post->read_password;
$isEditor = auth()->check() && (auth()->user()->isAdmin() || auth()->user()->hasRole('editor'));
if (! $granted && ! $isEditor) {
abort(403, '该文章需要访问密码');
}
}
}