You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.9KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Repositories;
  4. use App\Models\Campaign;
  5. use Core\Repository;
  6. class CampaignRepository extends Repository
  7. {
  8. protected string $table = 'campaign';
  9. protected string $primaryKey = 'id';
  10. /**
  11. * All campaigns joined with their campaign type name, ordered by id desc.
  12. *
  13. * @return list<array<string, mixed>>
  14. */
  15. public function allWithType(): array
  16. {
  17. return $this->database->query(
  18. 'SELECT c.id, c.campaign_type_id, c.attribute_values,
  19. c.created_at, c.updated_at,
  20. ct.name AS campaign_type_name,
  21. ct.attributes AS campaign_type_attributes
  22. FROM campaign c
  23. INNER JOIN campaign_type ct ON c.campaign_type_id = ct.id
  24. ORDER BY c.id DESC'
  25. );
  26. }
  27. /**
  28. * Single campaign joined with its campaign type name and attributes.
  29. */
  30. public function findWithType(int $id): ?array
  31. {
  32. return $this->database->first(
  33. 'SELECT c.id, c.campaign_type_id, c.attribute_values,
  34. c.created_at, c.updated_at,
  35. ct.name AS campaign_type_name,
  36. ct.attributes AS campaign_type_attributes
  37. FROM campaign c
  38. INNER JOIN campaign_type ct ON c.campaign_type_id = ct.id
  39. WHERE c.id = :id',
  40. ['id' => $id]
  41. );
  42. }
  43. /**
  44. * Return the most recently inserted campaign for a given type.
  45. * Used after an INSERT to retrieve the generated id for audit logging.
  46. */
  47. public function findLatestByType(int $typeId): ?array
  48. {
  49. return $this->database->first(
  50. 'SELECT TOP (1) * FROM campaign
  51. WHERE campaign_type_id = :type_id
  52. ORDER BY id DESC',
  53. ['type_id' => $typeId]
  54. );
  55. }
  56. public function create(Campaign $campaign): bool
  57. {
  58. return $this->database->execute(
  59. 'INSERT INTO campaign (campaign_type_id, attribute_values)
  60. VALUES (:campaign_type_id, :attribute_values)',
  61. [
  62. 'campaign_type_id' => $campaign->campaignTypeId,
  63. 'attribute_values' => json_encode($campaign->attributeValues, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  64. ]
  65. );
  66. }
  67. public function update(Campaign $campaign): bool
  68. {
  69. return $this->database->execute(
  70. 'UPDATE campaign
  71. SET campaign_type_id = :campaign_type_id,
  72. attribute_values = :attribute_values,
  73. updated_at = CURRENT_TIMESTAMP
  74. WHERE id = :id',
  75. [
  76. 'campaign_type_id' => $campaign->campaignTypeId,
  77. 'attribute_values' => json_encode($campaign->attributeValues, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  78. 'id' => $campaign->id,
  79. ]
  80. );
  81. }
  82. }

Powered by TurnKey Linux.