CategoriesController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Application\Admin;
  4. use App\Domain\Audit\AuditAction;
  5. use App\Domain\Audit\AuditEmitter;
  6. use App\Domain\Reputation\DecayFunction;
  7. use App\Infrastructure\Category\CategoryRepository;
  8. use Psr\Http\Message\ResponseInterface;
  9. use Psr\Http\Message\ServerRequestInterface;
  10. /**
  11. * Admin CRUD over `categories`. Slugs are kebab-case lowercase + unique;
  12. * decay function is `linear|exponential`; decay param is non-negative.
  13. *
  14. * Delete semantics (SPEC §M10.1):
  15. * - if the category is referenced by `policy_category_thresholds` OR
  16. * `reports`, refuse with 409 + a `usage` payload describing the
  17. * references. Soft-delete via `is_active=false` is the recommended
  18. * fallback (do that explicitly via PATCH).
  19. * - if no references exist, hard-delete.
  20. *
  21. * RBAC: list/show ⇒ Viewer; create/update/delete ⇒ Admin.
  22. */
  23. final class CategoriesController
  24. {
  25. use AdminControllerSupport;
  26. private const SLUG_PATTERN = '/^[a-z][a-z0-9_]{0,63}$/';
  27. public function __construct(
  28. private readonly CategoryRepository $categories,
  29. private readonly AuditEmitter $audit,
  30. ) {
  31. }
  32. public function list(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
  33. {
  34. $items = array_map(static fn ($c) => $c->toArray(), $this->categories->listAll());
  35. return self::json($response, 200, [
  36. 'items' => $items,
  37. 'total' => count($items),
  38. ]);
  39. }
  40. /**
  41. * @param array{id: string} $args
  42. */
  43. public function show(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
  44. {
  45. $id = self::parseId($args['id']);
  46. if ($id === null) {
  47. return self::error($response, 404, 'not_found');
  48. }
  49. $category = $this->categories->findById($id);
  50. if ($category === null) {
  51. return self::error($response, 404, 'not_found');
  52. }
  53. return self::json($response, 200, $category->toArray());
  54. }
  55. public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
  56. {
  57. $body = self::jsonBody($request);
  58. $errors = [];
  59. $slug = isset($body['slug']) && is_string($body['slug']) ? trim($body['slug']) : '';
  60. if ($slug === '' || preg_match(self::SLUG_PATTERN, $slug) !== 1) {
  61. $errors['slug'] = 'required, lowercase alpha + digits + underscore, ≤64 chars';
  62. } elseif ($this->categories->findBySlug($slug) !== null) {
  63. $errors['slug'] = 'already exists';
  64. }
  65. $name = isset($body['name']) && is_string($body['name']) ? trim($body['name']) : '';
  66. if ($name === '' || strlen($name) > 128) {
  67. $errors['name'] = 'required, 1–128 chars';
  68. }
  69. $description = null;
  70. if (array_key_exists('description', $body)) {
  71. if ($body['description'] !== null && !is_string($body['description'])) {
  72. $errors['description'] = 'must be string or null';
  73. } else {
  74. $description = $body['description'];
  75. }
  76. }
  77. $decayFunction = null;
  78. $rawFn = $body['decay_function'] ?? null;
  79. if (is_string($rawFn)) {
  80. $decayFunction = DecayFunction::tryFrom($rawFn);
  81. }
  82. if ($decayFunction === null) {
  83. $errors['decay_function'] = 'required, "linear" or "exponential"';
  84. }
  85. $decayParam = null;
  86. if (isset($body['decay_param']) && (is_int($body['decay_param']) || is_float($body['decay_param']))) {
  87. $decayParam = (float) $body['decay_param'];
  88. if ($decayParam <= 0) {
  89. $errors['decay_param'] = 'must be positive';
  90. }
  91. } else {
  92. $errors['decay_param'] = 'required, positive number';
  93. }
  94. $isActive = true;
  95. if (array_key_exists('is_active', $body)) {
  96. if (!is_bool($body['is_active'])) {
  97. $errors['is_active'] = 'must be boolean';
  98. } else {
  99. $isActive = $body['is_active'];
  100. }
  101. }
  102. if ($errors !== []) {
  103. return self::validationFailed($response, $errors);
  104. }
  105. /** @var DecayFunction $decayFunction */
  106. /** @var float $decayParam */
  107. $id = $this->categories->create($slug, $name, $description, $decayFunction, $decayParam, $isActive);
  108. $created = $this->categories->findById($id);
  109. if ($created === null) {
  110. return self::error($response, 500, 'create_failed');
  111. }
  112. $this->audit->emit(
  113. AuditAction::CATEGORY_CREATED,
  114. 'category',
  115. $id,
  116. ['slug' => $slug, 'name' => $name, 'decay_function' => $decayFunction->value, 'decay_param' => $decayParam],
  117. self::auditContext($request),
  118. $slug,
  119. );
  120. return self::json($response, 201, $created->toArray());
  121. }
  122. /**
  123. * @param array{id: string} $args
  124. */
  125. public function update(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
  126. {
  127. $id = self::parseId($args['id']);
  128. if ($id === null) {
  129. return self::error($response, 404, 'not_found');
  130. }
  131. $existing = $this->categories->findById($id);
  132. if ($existing === null) {
  133. return self::error($response, 404, 'not_found');
  134. }
  135. $body = self::jsonBody($request);
  136. $errors = [];
  137. $fields = [];
  138. if (array_key_exists('slug', $body)) {
  139. if (!is_string($body['slug']) || preg_match(self::SLUG_PATTERN, trim($body['slug'])) !== 1) {
  140. $errors['slug'] = 'lowercase alpha + digits + underscore, ≤64 chars';
  141. } else {
  142. $newSlug = trim($body['slug']);
  143. $other = $this->categories->findBySlug($newSlug);
  144. if ($other !== null && $other->id !== $id) {
  145. $errors['slug'] = 'already exists';
  146. } else {
  147. $fields['slug'] = $newSlug;
  148. }
  149. }
  150. }
  151. if (array_key_exists('name', $body)) {
  152. if (!is_string($body['name']) || trim($body['name']) === '' || strlen(trim($body['name'])) > 128) {
  153. $errors['name'] = 'required, 1–128 chars';
  154. } else {
  155. $fields['name'] = trim($body['name']);
  156. }
  157. }
  158. if (array_key_exists('description', $body)) {
  159. if ($body['description'] !== null && !is_string($body['description'])) {
  160. $errors['description'] = 'must be string or null';
  161. } else {
  162. $fields['description'] = $body['description'];
  163. }
  164. }
  165. if (array_key_exists('decay_function', $body)) {
  166. $fn = is_string($body['decay_function']) ? DecayFunction::tryFrom($body['decay_function']) : null;
  167. if ($fn === null) {
  168. $errors['decay_function'] = '"linear" or "exponential"';
  169. } else {
  170. $fields['decay_function'] = $fn->value;
  171. }
  172. }
  173. if (array_key_exists('decay_param', $body)) {
  174. if (is_int($body['decay_param']) || is_float($body['decay_param'])) {
  175. $value = (float) $body['decay_param'];
  176. if ($value <= 0) {
  177. $errors['decay_param'] = 'must be positive';
  178. } else {
  179. $fields['decay_param'] = number_format($value, 4, '.', '');
  180. }
  181. } else {
  182. $errors['decay_param'] = 'must be positive number';
  183. }
  184. }
  185. if (array_key_exists('is_active', $body)) {
  186. if (!is_bool($body['is_active'])) {
  187. $errors['is_active'] = 'must be boolean';
  188. } else {
  189. $fields['is_active'] = $body['is_active'] ? 1 : 0;
  190. }
  191. }
  192. if ($errors !== []) {
  193. return self::validationFailed($response, $errors);
  194. }
  195. $beforeSnapshot = [
  196. 'slug' => $existing->slug,
  197. 'name' => $existing->name,
  198. 'description' => $existing->description,
  199. 'decay_function' => $existing->decayFunction->value,
  200. 'decay_param' => number_format($existing->decayParam, 4, '.', ''),
  201. 'is_active' => $existing->isActive ? 1 : 0,
  202. ];
  203. $this->categories->update($id, $fields);
  204. $updated = $this->categories->findById($id);
  205. if ($updated === null) {
  206. return self::error($response, 500, 'update_failed');
  207. }
  208. $this->audit->emit(
  209. AuditAction::CATEGORY_UPDATED,
  210. 'category',
  211. $id,
  212. ['slug' => $existing->slug, 'changes' => self::diffFields($beforeSnapshot, $fields)],
  213. self::auditContext($request),
  214. $updated->slug,
  215. );
  216. return self::json($response, 200, $updated->toArray());
  217. }
  218. /**
  219. * @param array{id: string} $args
  220. */
  221. public function delete(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
  222. {
  223. $id = self::parseId($args['id']);
  224. if ($id === null) {
  225. return self::error($response, 404, 'not_found');
  226. }
  227. $existing = $this->categories->findById($id);
  228. if ($existing === null) {
  229. return self::error($response, 404, 'not_found');
  230. }
  231. $policyRefs = $this->categories->policyReferenceCount($id);
  232. $reportRefs = $this->categories->reportReferenceCount($id);
  233. if ($policyRefs > 0 || $reportRefs > 0) {
  234. return self::json($response, 409, [
  235. 'error' => 'category_in_use',
  236. 'usage' => [
  237. 'policies' => $policyRefs,
  238. 'reports' => $reportRefs,
  239. ],
  240. 'hint' => 'PATCH with is_active=false to soft-delete instead.',
  241. ]);
  242. }
  243. $this->categories->delete($id);
  244. $this->audit->emit(
  245. AuditAction::CATEGORY_DELETED,
  246. 'category',
  247. $id,
  248. ['slug' => $existing->slug, 'name' => $existing->name],
  249. self::auditContext($request),
  250. $existing->slug,
  251. );
  252. return $response->withStatus(204);
  253. }
  254. private static function parseId(string $raw): ?int
  255. {
  256. return preg_match('/^[1-9][0-9]*$/', $raw) === 1 ? (int) $raw : null;
  257. }
  258. }