CprModel.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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]);
  53. }
  54. public function create(array $data, int $statusId): 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 (!array_key_exists($column, $data)) {
  71. if ($info['nullable']) {
  72. $columns[] = '"' . $column . '"';
  73. $placeholders[] = ':' . $column;
  74. $params[$column] = null;
  75. continue;
  76. }
  77. throw new \InvalidArgumentException("Missing field: {$column}");
  78. }
  79. $value = $data[$column];
  80. if ($column === 'cpr_children_codes') {
  81. $value = $this->normalizeChildrenCodes($value);
  82. }
  83. $columns[] = '"' . $column . '"';
  84. $placeholders[] = ':' . $column;
  85. $params[$column] = $value;
  86. }
  87. $sql = 'INSERT INTO "cpr" (' . implode(', ', $columns) . ')
  88. VALUES (' . implode(', ', $placeholders) . ')
  89. RETURNING cpr_id';
  90. $stmt = $this->pdo->prepare($sql);
  91. $stmt->execute($params);
  92. $cprId = (int)$stmt->fetchColumn();
  93. $record = $this->fetchById($cprId);
  94. if (!$record) {
  95. throw new \RuntimeException('Failed to load created CPR record');
  96. }
  97. if (isset($record['cpr_children_codes'])) {
  98. $record['cpr_children_codes'] = $this->decodeChildrenCodes((string)$record['cpr_children_codes']);
  99. }
  100. $record['cpr_id'] = (int)$record['cpr_id'];
  101. if (isset($record['status_id'])) {
  102. $record['status_id'] = (int)$record['status_id'];
  103. }
  104. return $record;
  105. }
  106. private function normalizeChildrenCodes($value): string
  107. {
  108. if (is_array($value)) {
  109. $value = array_map('strval', array_values($value));
  110. if (!$value) {
  111. throw new \InvalidArgumentException('cpr_children_codes must not be empty');
  112. }
  113. $encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  114. if ($encoded === false) {
  115. throw new \InvalidArgumentException('Invalid cpr_children_codes payload');
  116. }
  117. return $encoded;
  118. }
  119. if (is_string($value) && trim($value) !== '') {
  120. return $value;
  121. }
  122. throw new \InvalidArgumentException('cpr_children_codes must be a non-empty string or array of strings');
  123. }
  124. /**
  125. * @return array<int, string>|string
  126. */
  127. private function decodeChildrenCodes(string $stored)
  128. {
  129. $decoded = json_decode($stored, true);
  130. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  131. return $decoded;
  132. }
  133. return $stored;
  134. }
  135. private function fetchById(int $id): ?array
  136. {
  137. $stmt = $this->pdo->prepare('SELECT * FROM "cpr" WHERE cpr_id = :id');
  138. $stmt->execute(['id' => $id]);
  139. $record = $stmt->fetch(\PDO::FETCH_ASSOC);
  140. return $record ?: null;
  141. }
  142. }