CprModel.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. namespace Models;
  3. class CprModel
  4. {
  5. private \PDO $pdo;
  6. private static ?array $columnsMeta = null;
  7. public function __construct()
  8. {
  9. if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
  10. $this->pdo = $GLOBALS['pdo'];
  11. return;
  12. }
  13. throw new \RuntimeException('Global PDO connection not initialized');
  14. }
  15. /**
  16. * @return array<string, array{nullable: bool, data_type: string}>
  17. */
  18. private function getColumnsMeta(): array
  19. {
  20. if (self::$columnsMeta !== null) {
  21. return self::$columnsMeta;
  22. }
  23. $stmt = $this->pdo->prepare(
  24. 'SELECT column_name, is_nullable, data_type
  25. FROM information_schema.columns
  26. WHERE table_schema = current_schema()
  27. AND table_name = :table
  28. ORDER BY ordinal_position'
  29. );
  30. $stmt->execute(['table' => 'cpr']);
  31. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
  32. if (!$rows) {
  33. throw new \RuntimeException('Unable to load CPR table metadata');
  34. }
  35. $meta = [];
  36. foreach ($rows as $row) {
  37. $meta[$row['column_name']] = [
  38. 'nullable' => strtoupper((string)$row['is_nullable']) === 'YES',
  39. 'data_type' => (string)$row['data_type'],
  40. ];
  41. }
  42. self::$columnsMeta = $meta;
  43. return self::$columnsMeta;
  44. }
  45. /**
  46. * @return array<string, array{nullable: bool, data_type: string}>
  47. */
  48. public function getUserColumns(): array
  49. {
  50. $meta = $this->getColumnsMeta();
  51. unset($meta['cpr_id']);
  52. return array_diff_key($meta, ['status_id' => true, 'payment_id' => true]);
  53. }
  54. public function create(array $data, int $statusId, int $paymentId): array
  55. {
  56. $meta = $this->getColumnsMeta();
  57. $columns = [];
  58. $placeholders = [];
  59. $params = [];
  60. foreach ($meta as $column => $info) {
  61. if ($column === 'cpr_id') {
  62. continue;
  63. }
  64. if ($column === 'status_id') {
  65. $columns[] = '"status_id"';
  66. $placeholders[] = ':status_id';
  67. $params['status_id'] = $statusId;
  68. continue;
  69. }
  70. if ($column === 'payment_id') {
  71. $columns[] = '"payment_id"';
  72. $placeholders[] = ':payment_id';
  73. $params['payment_id'] = $paymentId;
  74. continue;
  75. }
  76. if (!array_key_exists($column, $data)) {
  77. if ($info['nullable']) {
  78. $columns[] = '"' . $column . '"';
  79. $placeholders[] = ':' . $column;
  80. $params[$column] = null;
  81. continue;
  82. }
  83. throw new \InvalidArgumentException("Missing field: {$column}");
  84. }
  85. $value = $data[$column];
  86. if ($column === 'cpr_children_codes') {
  87. $value = $this->normalizeChildrenCodes($value);
  88. }
  89. $columns[] = '"' . $column . '"';
  90. $placeholders[] = ':' . $column;
  91. $params[$column] = $value;
  92. }
  93. $sql = 'INSERT INTO "cpr" (' . implode(', ', $columns) . ')
  94. VALUES (' . implode(', ', $placeholders) . ')
  95. RETURNING cpr_id';
  96. $stmt = $this->pdo->prepare($sql);
  97. $stmt->execute($params);
  98. $cprId = (int)$stmt->fetchColumn();
  99. $record = $this->fetchById($cprId);
  100. if (!$record) {
  101. throw new \RuntimeException('Failed to load created CPR record');
  102. }
  103. if (isset($record['cpr_children_codes'])) {
  104. $record['cpr_children_codes'] = $this->decodeChildrenCodes((string)$record['cpr_children_codes']);
  105. }
  106. $record['cpr_id'] = (int)$record['cpr_id'];
  107. if (isset($record['status_id'])) {
  108. $record['status_id'] = (int)$record['status_id'];
  109. }
  110. if (isset($record['payment_id'])) {
  111. $record['payment_id'] = (int)$record['payment_id'];
  112. }
  113. return $record;
  114. }
  115. private function normalizeChildrenCodes($value): string
  116. {
  117. if (is_array($value)) {
  118. $value = array_map('strval', array_values($value));
  119. if (!$value) {
  120. throw new \InvalidArgumentException('cpr_children_codes must not be empty');
  121. }
  122. $encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  123. if ($encoded === false) {
  124. throw new \InvalidArgumentException('Invalid cpr_children_codes payload');
  125. }
  126. return $encoded;
  127. }
  128. if (is_string($value) && trim($value) !== '') {
  129. return $value;
  130. }
  131. throw new \InvalidArgumentException('cpr_children_codes must be a non-empty string or array of strings');
  132. }
  133. /**
  134. * @return array<int, string>|string
  135. */
  136. private function decodeChildrenCodes(string $stored)
  137. {
  138. $decoded = json_decode($stored, true);
  139. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  140. return $decoded;
  141. }
  142. return $stored;
  143. }
  144. private function fetchById(int $id): ?array
  145. {
  146. $stmt = $this->pdo->prepare('SELECT * FROM "cpr" WHERE cpr_id = :id');
  147. $stmt->execute(['id' => $id]);
  148. $record = $stmt->fetch(\PDO::FETCH_ASSOC);
  149. return $record ?: null;
  150. }
  151. }