DocumentModel.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Models;
  3. class DocumentModel
  4. {
  5. private \PDO $pdo;
  6. public function __construct()
  7. {
  8. if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
  9. $this->pdo = $GLOBALS['pdo'];
  10. return;
  11. }
  12. }
  13. public function create(int $userId, string $documentType, string $documentPath): array
  14. {
  15. $stmt = $this->pdo->prepare(
  16. 'INSERT INTO "document" (user_id, document_type, document_path)
  17. VALUES (:user_id, :document_type, :document_path)
  18. RETURNING document_id'
  19. );
  20. $stmt->execute([
  21. 'user_id' => $userId,
  22. 'document_type' => $documentType,
  23. 'document_path' => $documentPath,
  24. ]);
  25. $documentId = (int)$stmt->fetchColumn();
  26. return [
  27. 'document_id' => $documentId,
  28. 'user_id' => $userId,
  29. 'document_type' => $documentType,
  30. 'document_path' => $documentPath,
  31. ];
  32. }
  33. public function listByUserId(int $userId): array
  34. {
  35. $stmt = $this->pdo->prepare(
  36. 'SELECT document_id, user_id, document_type, document_path
  37. FROM "document"
  38. WHERE user_id = :user_id
  39. ORDER BY document_id DESC'
  40. );
  41. $stmt->execute(['user_id' => $userId]);
  42. return $stmt->fetchAll(\PDO::FETCH_ASSOC);
  43. }
  44. public function findLatestByUserIdAndType(int $userId, string $documentType): ?array
  45. {
  46. $stmt = $this->pdo->prepare(
  47. 'SELECT document_id, user_id, document_type, document_path
  48. FROM "document"
  49. WHERE user_id = :user_id AND document_type = :document_type
  50. ORDER BY document_id DESC
  51. LIMIT 1'
  52. );
  53. $stmt->execute([
  54. 'user_id' => $userId,
  55. 'document_type' => $documentType,
  56. ]);
  57. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  58. return $row ?: null;
  59. }
  60. }