Posts module: posts, drafts and scheduling, categories and tags

This commit is contained in:
Matthijs Iriks committed 2026-12-04 01:33:59 +01:00
1 parent a9a1625241
commit e093614169
18 files changed
+977 -30

No files matched your search

+189
View File
@@ -0,0 +1,189 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Support\Markdown;
/**
* The posts. A post that is live or scheduled is only changed or deleted by who may publish: a
* change to it is on the site at once. Who may not publish only ever saves drafts.
*
* The answers have the shape the screens of the sites used as props.
*/
class PostController
{
public function __construct(private readonly PostLabels $labels) {}
public function index(): JsonResponse
{
$posts = Post::query()
->orderByRaw('published_at is null desc')
->latest('published_at')
->latest('id')
->get()
->map(fn (Post $post) => [
'id' => $post->id,
'title' => $post->title,
'slug' => $post->slug,
'category' => $post->category,
'is_featured' => $post->is_featured,
'status' => $post->status(),
'published_at' => $post->published_at?->toIso8601String(),
'can_change' => Gate::allows('posts.write') && $this->mayTouch($post),
'can_delete' => Gate::allows('posts.delete') && $this->mayTouch($post),
])
->values();
return response()->json(['posts' => $posts]);
}
public function create(): JsonResponse
{
return response()->json([
'post' => null,
'categories' => $this->labels->categories(),
'known_tags' => $this->labels->names(PostLabels::TAG),
]);
}
public function store(Request $request): JsonResponse
{
$post = Post::create($this->validated($request));
return response()->json(['id' => $post->id], 201);
}
public function edit(string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
abort_unless($this->mayTouch($post), 403);
return response()->json([
'post' => [
'id' => $post->id,
'title' => $post->title,
'slug' => $post->slug,
'excerpt' => $post->excerpt,
'body' => $post->body,
'cover_image' => $post->cover_image,
'category' => $post->category,
'tags' => $post->tags ?? [],
'is_featured' => $post->is_featured,
'is_published' => $post->published_at !== null,
// datetime-local value, in the app timezone
'published_at' => $post->published_at?->format('Y-m-d\TH:i'),
'status' => $post->status(),
],
'categories' => $this->labels->categories(),
'known_tags' => $this->labels->names(PostLabels::TAG),
]);
}
/** The post as a visitor will see it, also for drafts and scheduled posts. */
public function preview(string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
return response()->json(['post' => [...$post->toCard(), 'body_html' => Markdown::toHtml($post->body)], 'preview' => true]);
}
public function update(Request $request, string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
abort_unless($this->mayTouch($post), 403);
$post->update($this->validated($request, $post));
return response()->json(['saved' => true]);
}
/** Puts a post on the site, or takes it off again (a draft) without opening it. */
public function online(Request $request, string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
$request->validate(['online' => ['required', 'boolean']]);
$post->update(['published_at' => $request->boolean('online') ? ($post->published_at ?? now()) : null]);
return response()->json(['status' => $post->status()]);
}
public function destroy(string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
abort_unless($this->mayTouch($post), 403);
$post->delete();
return response()->json(['deleted' => true]);
}
/**
* Validates the post form and turns it into model attributes.
*
* @return array<string, mixed>
*/
private function validated(Request $request, ?Post $post = null): array
{
$request->validate([
'title' => ['required', 'string', 'max:255'],
'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(config('manager.table_prefix').'posts', 'slug')->ignore($post?->id)],
'excerpt' => ['nullable', 'string', 'max:500'],
'body' => ['required', 'string'],
'cover_image' => ['nullable', 'string', 'max:2048'],
'category' => ['nullable', 'string', 'max:60'],
'tags' => ['array', 'max:20'],
'tags.*' => ['nullable', 'string', 'max:40'],
'is_featured' => ['boolean'],
'is_published' => ['boolean'],
'published_at' => ['nullable', 'date'],
], [
'slug.regex' => 'Use only lowercase letters, numbers and dashes.',
]);
$title = $request->string('title')->trim()->toString();
$slug = $request->string('slug')->trim()->toString();
// Publishing without a date means "now"; a date in the future schedules the post.
// Who may not publish only gets a draft, and a post that was live is not touched
// (mayTouch refused that before we got here).
$publishedAt = null;
if ($request->boolean('is_published') && Gate::allows('posts.publish')) {
$date = $request->string('published_at')->toString();
$publishedAt = $date !== '' ? Carbon::parse($date) : ($post?->published_at ?? now());
}
return [
'title' => $title,
'slug' => $slug !== '' ? $slug : Post::uniqueSlug($title, $post?->id),
'excerpt' => $this->nullableString($request, 'excerpt'),
'body' => $request->string('body')->toString(),
'cover_image' => $this->nullableString($request, 'cover_image'),
'category' => $this->nullableString($request, 'category'),
'tags' => array_values(array_filter(array_map(
fn (mixed $tag) => is_string($tag) ? trim($tag) : '',
$request->array('tags'),
))),
'is_featured' => $request->boolean('is_featured'),
'published_at' => $publishedAt,
];
}
private function mayTouch(Post $post): bool
{
return $post->published_at === null || Gate::allows('posts.publish');
}
private function nullableString(Request $request, string $key): ?string
{
$value = $request->string($key)->trim()->toString();
return $value !== '' ? $value : null;
}
}