PolicyRepository.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Infrastructure\Policy;
  4. use App\Domain\Policy\Policy;
  5. use App\Infrastructure\Db\RepositoryBase;
  6. use DateTimeImmutable;
  7. use DateTimeZone;
  8. use Doctrine\DBAL\Connection;
  9. /**
  10. * DBAL gateway for `policies` and `policy_category_thresholds`.
  11. *
  12. * Threshold rows live in a separate join table but the policy makes no
  13. * sense without them: every read loads a policy together with all its
  14. * thresholds in a small two-query fetch. Writes that touch thresholds
  15. * happen inside a single transaction (see `replaceThresholds`).
  16. */
  17. final class PolicyRepository extends RepositoryBase
  18. {
  19. public function findById(int $id): ?Policy
  20. {
  21. /** @var array<string, mixed>|false $row */
  22. $row = $this->connection()->fetchAssociative(
  23. 'SELECT id, name, description, include_manual_blocks, created_at FROM policies WHERE id = :id',
  24. ['id' => $id]
  25. );
  26. if ($row === false) {
  27. return null;
  28. }
  29. return $this->hydrate($row, $this->loadThresholds((int) $row['id']));
  30. }
  31. public function findByName(string $name): ?Policy
  32. {
  33. /** @var array<string, mixed>|false $row */
  34. $row = $this->connection()->fetchAssociative(
  35. 'SELECT id, name, description, include_manual_blocks, created_at FROM policies WHERE name = :name',
  36. ['name' => $name]
  37. );
  38. if ($row === false) {
  39. return null;
  40. }
  41. return $this->hydrate($row, $this->loadThresholds((int) $row['id']));
  42. }
  43. /**
  44. * @return list<Policy>
  45. */
  46. public function listAll(): array
  47. {
  48. /** @var list<array<string, mixed>> $rows */
  49. $rows = $this->connection()->fetchAllAssociative(
  50. 'SELECT id, name, description, include_manual_blocks, created_at FROM policies ORDER BY id ASC'
  51. );
  52. if ($rows === []) {
  53. return [];
  54. }
  55. $thresholdsByPolicy = $this->loadAllThresholds();
  56. return array_map(
  57. fn (array $row): Policy => $this->hydrate($row, $thresholdsByPolicy[(int) $row['id']] ?? []),
  58. $rows
  59. );
  60. }
  61. /**
  62. * Insert a policy + its thresholds atomically. Returns the new id.
  63. *
  64. * @param array<int, float> $thresholds category_id => threshold
  65. */
  66. public function create(string $name, ?string $description, bool $includeManualBlocks, array $thresholds): int
  67. {
  68. return (int) $this->connection()->transactional(function (Connection $conn) use ($name, $description, $includeManualBlocks, $thresholds): int {
  69. $conn->insert('policies', [
  70. 'name' => $name,
  71. 'description' => $description,
  72. 'include_manual_blocks' => $includeManualBlocks ? 1 : 0,
  73. ]);
  74. $policyId = (int) $conn->lastInsertId();
  75. foreach ($thresholds as $categoryId => $threshold) {
  76. $conn->insert('policy_category_thresholds', [
  77. 'policy_id' => $policyId,
  78. 'category_id' => $categoryId,
  79. 'threshold' => number_format($threshold, 4, '.', ''),
  80. ]);
  81. }
  82. return $policyId;
  83. });
  84. }
  85. /**
  86. * Replace the policy's name/description/include_manual_blocks fields.
  87. * Only the keys present in `$fields` are updated.
  88. *
  89. * @param array<string, mixed> $fields
  90. */
  91. public function update(int $id, array $fields): void
  92. {
  93. if ($fields === []) {
  94. return;
  95. }
  96. $this->connection()->update('policies', $fields, ['id' => $id]);
  97. }
  98. /**
  99. * Atomic threshold replacement: deletes the old set and inserts the new
  100. * one inside a single transaction so concurrent updates can't observe a
  101. * half-written state.
  102. *
  103. * @param array<int, float> $thresholds category_id => threshold
  104. */
  105. public function replaceThresholds(int $policyId, array $thresholds): void
  106. {
  107. $this->connection()->transactional(function (Connection $conn) use ($policyId, $thresholds): void {
  108. $conn->executeStatement(
  109. 'DELETE FROM policy_category_thresholds WHERE policy_id = :pid',
  110. ['pid' => $policyId]
  111. );
  112. foreach ($thresholds as $categoryId => $threshold) {
  113. $conn->insert('policy_category_thresholds', [
  114. 'policy_id' => $policyId,
  115. 'category_id' => $categoryId,
  116. 'threshold' => number_format($threshold, 4, '.', ''),
  117. ]);
  118. }
  119. });
  120. }
  121. public function delete(int $id): void
  122. {
  123. $this->connection()->executeStatement('DELETE FROM policies WHERE id = :id', ['id' => $id]);
  124. }
  125. /**
  126. * Returns active consumers (id + name) referencing this policy. The
  127. * admin DELETE endpoint uses this list to refuse deletion with a 409
  128. * response (per SPEC §M07: cascade is wrong here).
  129. *
  130. * @return list<array{id: int, name: string}>
  131. */
  132. public function consumersUsing(int $policyId): array
  133. {
  134. /** @var list<array<string, mixed>> $rows */
  135. $rows = $this->connection()->fetchAllAssociative(
  136. 'SELECT id, name FROM consumers WHERE policy_id = :pid ORDER BY id ASC',
  137. ['pid' => $policyId]
  138. );
  139. return array_map(
  140. static fn (array $r): array => ['id' => (int) $r['id'], 'name' => (string) $r['name']],
  141. $rows
  142. );
  143. }
  144. /**
  145. * @return array<int, float> category_id => threshold
  146. */
  147. private function loadThresholds(int $policyId): array
  148. {
  149. /** @var list<array<string, mixed>> $rows */
  150. $rows = $this->connection()->fetchAllAssociative(
  151. 'SELECT category_id, threshold FROM policy_category_thresholds WHERE policy_id = :pid',
  152. ['pid' => $policyId]
  153. );
  154. $out = [];
  155. foreach ($rows as $row) {
  156. $out[(int) $row['category_id']] = (float) $row['threshold'];
  157. }
  158. return $out;
  159. }
  160. /**
  161. * @return array<int, array<int, float>> policy_id => (category_id => threshold)
  162. */
  163. private function loadAllThresholds(): array
  164. {
  165. /** @var list<array<string, mixed>> $rows */
  166. $rows = $this->connection()->fetchAllAssociative(
  167. 'SELECT policy_id, category_id, threshold FROM policy_category_thresholds'
  168. );
  169. $out = [];
  170. foreach ($rows as $row) {
  171. $out[(int) $row['policy_id']][(int) $row['category_id']] = (float) $row['threshold'];
  172. }
  173. return $out;
  174. }
  175. /**
  176. * @param array<string, mixed> $row
  177. * @param array<int, float> $thresholds
  178. */
  179. private function hydrate(array $row, array $thresholds): Policy
  180. {
  181. $createdAt = isset($row['created_at']) && $row['created_at'] !== null
  182. ? new DateTimeImmutable((string) $row['created_at'], new DateTimeZone('UTC'))
  183. : new DateTimeImmutable('now', new DateTimeZone('UTC'));
  184. return new Policy(
  185. id: (int) $row['id'],
  186. name: (string) $row['name'],
  187. description: $row['description'] !== null ? (string) $row['description'] : null,
  188. includeManualBlocks: (bool) $row['include_manual_blocks'],
  189. thresholds: $thresholds,
  190. createdAt: $createdAt,
  191. );
  192. }
  193. }