CprModel.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. $data = $this->flattenB3Arrays($data);
  57. $meta = $this->getColumnsMeta();
  58. $columns = [];
  59. $placeholders = [];
  60. $params = [];
  61. foreach ($meta as $column => $info) {
  62. if ($column === 'cpr_id') {
  63. continue;
  64. }
  65. if ($column === 'status_id') {
  66. $columns[] = '"status_id"';
  67. $placeholders[] = ':status_id';
  68. $params['status_id'] = $statusId;
  69. continue;
  70. }
  71. if ($column === 'payment_id') {
  72. $columns[] = '"payment_id"';
  73. $placeholders[] = ':payment_id';
  74. $params['payment_id'] = $paymentId;
  75. continue;
  76. }
  77. if (!array_key_exists($column, $data)) {
  78. if ($info['nullable']) {
  79. $columns[] = '"' . $column . '"';
  80. $placeholders[] = ':' . $column;
  81. $params[$column] = null;
  82. continue;
  83. }
  84. throw new \InvalidArgumentException("Missing field: {$column}");
  85. }
  86. $value = $data[$column];
  87. if ($column === 'cpr_children_codes') {
  88. $value = $this->normalizeChildrenCodes($value);
  89. }
  90. if (in_array($column, $this->getSemicolonListColumns(), true)) {
  91. $value = $this->normalizeSemicolonList($value, $column);
  92. }
  93. $columns[] = '"' . $column . '"';
  94. $placeholders[] = ':' . $column;
  95. $params[$column] = $value;
  96. }
  97. $sql = 'INSERT INTO "cpr" (' . implode(', ', $columns) . ')
  98. VALUES (' . implode(', ', $placeholders) . ')
  99. RETURNING cpr_id';
  100. $stmt = $this->pdo->prepare($sql);
  101. $stmt->execute($params);
  102. $cprId = (int)$stmt->fetchColumn();
  103. $record = $this->fetchById($cprId);
  104. if (!$record) {
  105. throw new \RuntimeException('Failed to load created CPR record');
  106. }
  107. if (isset($record['cpr_children_codes'])) {
  108. $record['cpr_children_codes'] = $this->decodeChildrenCodes((string)$record['cpr_children_codes']);
  109. }
  110. $record['cpr_id'] = (int)$record['cpr_id'];
  111. if (isset($record['status_id'])) {
  112. $record['status_id'] = (int)$record['status_id'];
  113. }
  114. if (isset($record['payment_id'])) {
  115. $record['payment_id'] = (int)$record['payment_id'];
  116. }
  117. return $record;
  118. }
  119. private function normalizeChildrenCodes($value): string
  120. {
  121. if (is_array($value)) {
  122. $value = array_map('strval', array_values($value));
  123. if (!$value) {
  124. throw new \InvalidArgumentException('cpr_children_codes must not be empty');
  125. }
  126. $encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  127. if ($encoded === false) {
  128. throw new \InvalidArgumentException('Invalid cpr_children_codes payload');
  129. }
  130. return $encoded;
  131. }
  132. if (is_string($value) && trim($value) !== '') {
  133. return $value;
  134. }
  135. throw new \InvalidArgumentException('cpr_children_codes must be a non-empty string or array of strings');
  136. }
  137. private function normalizeSemicolonList($value, string $field): string
  138. {
  139. if (is_array($value)) {
  140. $items = array_map(static fn($v) => trim((string)$v), array_values($value));
  141. $items = array_values(array_filter($items, static fn($v) => $v !== ''));
  142. if (!$items) {
  143. throw new \InvalidArgumentException("{$field} must not be empty");
  144. }
  145. return implode('; ', $items);
  146. }
  147. if (is_string($value)) {
  148. $trimmed = trim($value);
  149. if ($trimmed === '') {
  150. throw new \InvalidArgumentException("{$field} must not be empty");
  151. }
  152. $parts = preg_split('/\s*;\s*/', $trimmed) ?: [];
  153. $parts = array_map(static fn($v) => trim((string)$v), $parts);
  154. $parts = array_values(array_filter($parts, static fn($v) => $v !== ''));
  155. return implode('; ', $parts);
  156. }
  157. throw new \InvalidArgumentException("{$field} must be a non-empty string or array of strings");
  158. }
  159. private function getSemicolonListColumns(): array
  160. {
  161. return [
  162. 'cpr_collateral_type_code',
  163. 'cpr_collateral_type_name',
  164. 'cpr_constitution_process_indicator',
  165. 'cpr_otc_bondsman_account_code',
  166. 'cpr_issuer_name',
  167. 'cpr_issuers_document_number',
  168. 'cpr_issuers_person_type_acronym',
  169. 'cpr_issuer_legal_nature_code',
  170. 'cpr_issuers_state_acronym',
  171. 'cpr_issuers_city_name',
  172. 'cpr_production_place_name',
  173. 'cpr_property_registration_number',
  174. 'cpr_notary_name',
  175. 'cpr_total_production_area_in_hectares_number',
  176. 'cpr_total_area_in_hectares_number',
  177. 'cpr_car_code',
  178. 'cpr_latitude_code',
  179. 'cpr_longitude_code',
  180. 'cpr_zip_code',
  181. ];
  182. }
  183. private function flattenB3Arrays(array $data): array
  184. {
  185. if (!array_key_exists('collaterals', $data) && !array_key_exists('issuers', $data) && !array_key_exists('productionPlaces', $data)) {
  186. return $data;
  187. }
  188. if (array_key_exists('collaterals', $data) && !array_key_exists('cpr_collateral_type_code', $data)) {
  189. $collaterals = $data['collaterals'];
  190. if (is_array($collaterals) && $collaterals && $this->isAssoc($collaterals)) {
  191. $collaterals = [$collaterals];
  192. }
  193. if (is_array($collaterals)) {
  194. $data['cpr_collateral_type_code'] = array_map(static fn($c) => $c['collateralTypeCode'] ?? null, $collaterals);
  195. $data['cpr_collateral_type_name'] = array_map(static fn($c) => $c['collateralTypeName'] ?? null, $collaterals);
  196. $data['cpr_constitution_process_indicator'] = array_map(static fn($c) => $c['constitutionProcessIndicator'] ?? null, $collaterals);
  197. $data['cpr_otc_bondsman_account_code'] = array_map(static fn($c) => $c['otcBondsmanAccountCode'] ?? null, $collaterals);
  198. }
  199. }
  200. if (array_key_exists('issuers', $data) && !array_key_exists('cpr_issuer_name', $data)) {
  201. $issuers = $data['issuers'];
  202. if (is_array($issuers) && $issuers && $this->isAssoc($issuers)) {
  203. $issuers = [$issuers];
  204. }
  205. if (is_array($issuers)) {
  206. $data['cpr_issuer_name'] = array_map(static fn($i) => $i['cprIssuerName'] ?? null, $issuers);
  207. $data['cpr_issuers_document_number'] = array_map(static fn($i) => $i['documentNumber'] ?? null, $issuers);
  208. $data['cpr_issuers_person_type_acronym'] = array_map(static fn($i) => $i['personTypeAcronym'] ?? null, $issuers);
  209. $data['cpr_issuer_legal_nature_code'] = array_map(static fn($i) => $i['issuerLegalNatureCode'] ?? null, $issuers);
  210. $data['cpr_issuers_state_acronym'] = array_map(static fn($i) => $i['stateAcronym'] ?? null, $issuers);
  211. $data['cpr_issuers_city_name'] = array_map(static fn($i) => $i['cityName'] ?? null, $issuers);
  212. }
  213. }
  214. if (array_key_exists('productionPlaces', $data) && !array_key_exists('cpr_production_place_name', $data)) {
  215. $productionPlaces = $data['productionPlaces'];
  216. if (is_array($productionPlaces) && $productionPlaces && $this->isAssoc($productionPlaces)) {
  217. $productionPlaces = [$productionPlaces];
  218. }
  219. if (is_array($productionPlaces)) {
  220. $data['cpr_production_place_name'] = array_map(static fn($p) => $p['productionPlaceName'] ?? null, $productionPlaces);
  221. $data['cpr_property_registration_number'] = array_map(static fn($p) => $p['propertyRegistrationNumber'] ?? null, $productionPlaces);
  222. $data['cpr_notary_name'] = array_map(static fn($p) => $p['notaryName'] ?? null, $productionPlaces);
  223. $data['cpr_total_production_area_in_hectares_number'] = array_map(static fn($p) => $p['totalProductionAreaInHectaresNumber'] ?? null, $productionPlaces);
  224. $data['cpr_total_area_in_hectares_number'] = array_map(static fn($p) => $p['totalAreaInHectaresNumber'] ?? null, $productionPlaces);
  225. $data['cpr_car_code'] = array_map(static fn($p) => $p['carCode'] ?? null, $productionPlaces);
  226. $data['cpr_latitude_code'] = array_map(static fn($p) => $p['latitudeCode'] ?? null, $productionPlaces);
  227. $data['cpr_longitude_code'] = array_map(static fn($p) => $p['longitudeCode'] ?? null, $productionPlaces);
  228. $data['cpr_zip_code'] = array_map(static fn($p) => $p['zipCode'] ?? null, $productionPlaces);
  229. }
  230. }
  231. return $data;
  232. }
  233. private function isAssoc(array $arr): bool
  234. {
  235. return array_keys($arr) !== range(0, count($arr) - 1);
  236. }
  237. /**
  238. * @return array<int, string>|string
  239. */
  240. private function decodeChildrenCodes(string $stored)
  241. {
  242. $decoded = json_decode($stored, true);
  243. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  244. return $decoded;
  245. }
  246. return $stored;
  247. }
  248. private function fetchById(int $id): ?array
  249. {
  250. $stmt = $this->pdo->prepare('SELECT * FROM "cpr" WHERE cpr_id = :id');
  251. $stmt->execute(['id' => $id]);
  252. $record = $stmt->fetch(\PDO::FETCH_ASSOC);
  253. return $record ?: null;
  254. }
  255. }