51 lines
1.2 KiB
PHP
51 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Blog\Controllers;
|
|
|
|
use App\Blog\Services\PostContentRenderer;
|
|
use App\Models\Post;
|
|
|
|
class PostController extends Controller
|
|
{
|
|
public function __construct(private PostContentRenderer $renderer)
|
|
{
|
|
}
|
|
|
|
public function show(string $slug)
|
|
{
|
|
$post = Post::query()
|
|
->where('slug', $slug)
|
|
->orWhere('id', (int) $slug)
|
|
->first();
|
|
|
|
abort_unless($post && $post->status === 'published', 404);
|
|
|
|
$this->ensureReadable($post);
|
|
|
|
$post->increment('views');
|
|
|
|
$comments = $post->comments()
|
|
->where('status', 'published')
|
|
->latest('created_at')
|
|
->paginate(20);
|
|
|
|
$contentHtml = $this->renderer->render($post);
|
|
|
|
return theme_view('show', compact('post', 'comments', 'contentHtml'));
|
|
}
|
|
|
|
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, '该文章需要访问密码');
|
|
}
|
|
}
|
|
}
|