json($this->labels->overview()); } /** A category or tag that no post uses yet; the post form offers it from then on. */ public function store(Request $request): JsonResponse { $type = $this->type($request); $request->validate(['name' => $this->nameRules($type)], $this->messages()); $name = $request->string('name')->trim()->toString(); if (! $this->labels->create($type, $name)) { return response()->json(['message' => "The {$type} \"{$name}\" already exists.", 'errors' => ['name' => ["The {$type} \"{$name}\" already exists."]]], 422); } return response()->json(['created' => $name], 201); } public function update(Request $request): JsonResponse { $type = $this->type($request); $request->validate(['name' => ['required', 'string'], 'new_name' => $this->nameRules($type)], $this->messages()); $from = $request->string('name')->toString(); $to = $request->string('new_name')->trim()->toString(); return response()->json(['posts' => $this->labels->rename($type, $from, $to)]); } public function destroy(Request $request): JsonResponse { $type = $this->type($request); $request->validate(['name' => ['required', 'string']]); return response()->json(['posts' => $this->labels->remove($type, $request->string('name')->toString())]); } /** * The same limits as the post form. * * @return list */ private function nameRules(string $type): array { return ['required', 'string', 'max:'.($type === PostLabels::CATEGORY ? 60 : 40), ...($type === PostLabels::TAG ? ['not_regex:/,/'] : [])]; } /** @return array */ private function messages(): array { $comma = 'A tag cannot hold a comma: the post form separates tags with it.'; return ['name.not_regex' => $comma, 'new_name.not_regex' => $comma]; } private function type(Request $request): string { $request->validate(['type' => ['required', Rule::in([PostLabels::CATEGORY, PostLabels::TAG])]]); return $request->string('type')->toString(); } }