| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- <?php
- declare(strict_types=1);
- namespace App\Application\Admin;
- use App\Domain\Audit\AuditAction;
- use App\Domain\Audit\AuditEmitter;
- use App\Domain\Reputation\DecayFunction;
- use App\Infrastructure\Category\CategoryRepository;
- use Psr\Http\Message\ResponseInterface;
- use Psr\Http\Message\ServerRequestInterface;
- /**
- * Admin CRUD over `categories`. Slugs are kebab-case lowercase + unique;
- * decay function is `linear|exponential`; decay param is non-negative.
- *
- * Delete semantics (SPEC §M10.1):
- * - if the category is referenced by `policy_category_thresholds` OR
- * `reports`, refuse with 409 + a `usage` payload describing the
- * references. Soft-delete via `is_active=false` is the recommended
- * fallback (do that explicitly via PATCH).
- * - if no references exist, hard-delete.
- *
- * RBAC: list/show ⇒ Viewer; create/update/delete ⇒ Admin.
- */
- final class CategoriesController
- {
- use AdminControllerSupport;
- private const SLUG_PATTERN = '/^[a-z][a-z0-9_]{0,63}$/';
- public function __construct(
- private readonly CategoryRepository $categories,
- private readonly AuditEmitter $audit,
- ) {
- }
- public function list(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
- {
- $items = array_map(static fn ($c) => $c->toArray(), $this->categories->listAll());
- return self::json($response, 200, [
- 'items' => $items,
- 'total' => count($items),
- ]);
- }
- /**
- * @param array{id: string} $args
- */
- public function show(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
- {
- $id = self::parseId($args['id']);
- if ($id === null) {
- return self::error($response, 404, 'not_found');
- }
- $category = $this->categories->findById($id);
- if ($category === null) {
- return self::error($response, 404, 'not_found');
- }
- return self::json($response, 200, $category->toArray());
- }
- public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
- {
- $body = self::jsonBody($request);
- $errors = [];
- $slug = isset($body['slug']) && is_string($body['slug']) ? trim($body['slug']) : '';
- if ($slug === '' || preg_match(self::SLUG_PATTERN, $slug) !== 1) {
- $errors['slug'] = 'required, lowercase alpha + digits + underscore, ≤64 chars';
- } elseif ($this->categories->findBySlug($slug) !== null) {
- $errors['slug'] = 'already exists';
- }
- $name = isset($body['name']) && is_string($body['name']) ? trim($body['name']) : '';
- if ($name === '' || strlen($name) > 128) {
- $errors['name'] = 'required, 1–128 chars';
- }
- $description = null;
- if (array_key_exists('description', $body)) {
- if ($body['description'] !== null && !is_string($body['description'])) {
- $errors['description'] = 'must be string or null';
- } else {
- $description = $body['description'];
- }
- }
- $decayFunction = null;
- $rawFn = $body['decay_function'] ?? null;
- if (is_string($rawFn)) {
- $decayFunction = DecayFunction::tryFrom($rawFn);
- }
- if ($decayFunction === null) {
- $errors['decay_function'] = 'required, "linear" or "exponential"';
- }
- $decayParam = null;
- if (isset($body['decay_param']) && (is_int($body['decay_param']) || is_float($body['decay_param']))) {
- $decayParam = (float) $body['decay_param'];
- if ($decayParam <= 0) {
- $errors['decay_param'] = 'must be positive';
- }
- } else {
- $errors['decay_param'] = 'required, positive number';
- }
- $isActive = true;
- if (array_key_exists('is_active', $body)) {
- if (!is_bool($body['is_active'])) {
- $errors['is_active'] = 'must be boolean';
- } else {
- $isActive = $body['is_active'];
- }
- }
- if ($errors !== []) {
- return self::validationFailed($response, $errors);
- }
- /** @var DecayFunction $decayFunction */
- /** @var float $decayParam */
- $id = $this->categories->create($slug, $name, $description, $decayFunction, $decayParam, $isActive);
- $created = $this->categories->findById($id);
- if ($created === null) {
- return self::error($response, 500, 'create_failed');
- }
- $this->audit->emit(
- AuditAction::CATEGORY_CREATED,
- 'category',
- $id,
- ['slug' => $slug, 'name' => $name, 'decay_function' => $decayFunction->value, 'decay_param' => $decayParam],
- self::auditContext($request),
- $slug,
- );
- return self::json($response, 201, $created->toArray());
- }
- /**
- * @param array{id: string} $args
- */
- public function update(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
- {
- $id = self::parseId($args['id']);
- if ($id === null) {
- return self::error($response, 404, 'not_found');
- }
- $existing = $this->categories->findById($id);
- if ($existing === null) {
- return self::error($response, 404, 'not_found');
- }
- $body = self::jsonBody($request);
- $errors = [];
- $fields = [];
- if (array_key_exists('slug', $body)) {
- if (!is_string($body['slug']) || preg_match(self::SLUG_PATTERN, trim($body['slug'])) !== 1) {
- $errors['slug'] = 'lowercase alpha + digits + underscore, ≤64 chars';
- } else {
- $newSlug = trim($body['slug']);
- $other = $this->categories->findBySlug($newSlug);
- if ($other !== null && $other->id !== $id) {
- $errors['slug'] = 'already exists';
- } else {
- $fields['slug'] = $newSlug;
- }
- }
- }
- if (array_key_exists('name', $body)) {
- if (!is_string($body['name']) || trim($body['name']) === '' || strlen(trim($body['name'])) > 128) {
- $errors['name'] = 'required, 1–128 chars';
- } else {
- $fields['name'] = trim($body['name']);
- }
- }
- if (array_key_exists('description', $body)) {
- if ($body['description'] !== null && !is_string($body['description'])) {
- $errors['description'] = 'must be string or null';
- } else {
- $fields['description'] = $body['description'];
- }
- }
- if (array_key_exists('decay_function', $body)) {
- $fn = is_string($body['decay_function']) ? DecayFunction::tryFrom($body['decay_function']) : null;
- if ($fn === null) {
- $errors['decay_function'] = '"linear" or "exponential"';
- } else {
- $fields['decay_function'] = $fn->value;
- }
- }
- if (array_key_exists('decay_param', $body)) {
- if (is_int($body['decay_param']) || is_float($body['decay_param'])) {
- $value = (float) $body['decay_param'];
- if ($value <= 0) {
- $errors['decay_param'] = 'must be positive';
- } else {
- $fields['decay_param'] = number_format($value, 4, '.', '');
- }
- } else {
- $errors['decay_param'] = 'must be positive number';
- }
- }
- if (array_key_exists('is_active', $body)) {
- if (!is_bool($body['is_active'])) {
- $errors['is_active'] = 'must be boolean';
- } else {
- $fields['is_active'] = $body['is_active'] ? 1 : 0;
- }
- }
- if ($errors !== []) {
- return self::validationFailed($response, $errors);
- }
- $beforeSnapshot = [
- 'slug' => $existing->slug,
- 'name' => $existing->name,
- 'description' => $existing->description,
- 'decay_function' => $existing->decayFunction->value,
- 'decay_param' => number_format($existing->decayParam, 4, '.', ''),
- 'is_active' => $existing->isActive ? 1 : 0,
- ];
- $this->categories->update($id, $fields);
- $updated = $this->categories->findById($id);
- if ($updated === null) {
- return self::error($response, 500, 'update_failed');
- }
- $this->audit->emit(
- AuditAction::CATEGORY_UPDATED,
- 'category',
- $id,
- ['slug' => $existing->slug, 'changes' => self::diffFields($beforeSnapshot, $fields)],
- self::auditContext($request),
- $updated->slug,
- );
- return self::json($response, 200, $updated->toArray());
- }
- /**
- * @param array{id: string} $args
- */
- public function delete(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
- {
- $id = self::parseId($args['id']);
- if ($id === null) {
- return self::error($response, 404, 'not_found');
- }
- $existing = $this->categories->findById($id);
- if ($existing === null) {
- return self::error($response, 404, 'not_found');
- }
- $policyRefs = $this->categories->policyReferenceCount($id);
- $reportRefs = $this->categories->reportReferenceCount($id);
- if ($policyRefs > 0 || $reportRefs > 0) {
- return self::json($response, 409, [
- 'error' => 'category_in_use',
- 'usage' => [
- 'policies' => $policyRefs,
- 'reports' => $reportRefs,
- ],
- 'hint' => 'PATCH with is_active=false to soft-delete instead.',
- ]);
- }
- $this->categories->delete($id);
- $this->audit->emit(
- AuditAction::CATEGORY_DELETED,
- 'category',
- $id,
- ['slug' => $existing->slug, 'name' => $existing->name],
- self::auditContext($request),
- $existing->slug,
- );
- return $response->withStatus(204);
- }
- private static function parseId(string $raw): ?int
- {
- return preg_match('/^[1-9][0-9]*$/', $raw) === 1 ? (int) $raw : null;
- }
- }
|