Skip to content

Commit

Permalink
MMB-284: Handle multiple active memberships for a contact
Browse files Browse the repository at this point in the history
  • Loading branch information
shahrukh-moby committed Nov 7, 2023
1 parent 1c57150 commit d814f20
Showing 1 changed file with 21 additions and 16 deletions.
37 changes: 21 additions & 16 deletions CRM/Certificate/Token/Certificate.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use Civi\Token\Event\TokenValueEvent;
use Civi\Api4\Membership;

/**
* Class CRM_Certificate_Token_Certificate
Expand All @@ -13,6 +14,8 @@ class CRM_Certificate_Token_Certificate extends CRM_Certificate_Token_AbstractCe

const TOKEN = 'certificate';

private const MEMBERSHIP_STATUS_CURRENT = 2;

/**
* Here we define list of standard certificate configuration fields
* that are supported as tokens.
Expand Down Expand Up @@ -69,25 +72,27 @@ public function prefetch(TokenValueEvent $e) {
}

private function getMembershipDates(TokenValueEvent $e): array {
$startDate = NULL;
$endDate = NULL;

$contactIds = $e->getTokenProcessor()->getContextValues('contactId');
$contactId = (is_array($contactIds) && !empty($contactIds[0])) ? $contactIds[0] : 0;

$membershipRows = civicrm_api3(
'membership',
'get',
[
'version' => 3,
'return' => ['start_date', 'end_date'],
'contact_id' => $contactId,
'status_id' => 'Current',
'sequential' => 1,
'options' => ['sort' => 'end_date desc', 'limit' => 1],
]
);

return !empty($membershipRows['values'][0])
? $membershipRows['values'][0]
: ['start_date' => '', 'end_date' => ''];
$memberships = Membership::get(FALSE)
->addSelect('start_date', 'end_date')
->addWhere('contact_id', '=', $contactId)
->addWhere('status_id', '=', self::MEMBERSHIP_STATUS_CURRENT)
->execute()
->getArrayCopy();

foreach ($memberships as $membership) {
$startDate = $startDate === NULL || strtotime($membership['start_date']) < strtotime($startDate) ?
$membership['start_date'] : $startDate;
$endDate = $endDate === NULL || strtotime($membership['end_date']) > strtotime($endDate) ?
$membership['end_date'] : $endDate;
}

return ['start_date' => $startDate, 'end_date' => $endDate];
}

/**
Expand Down

0 comments on commit d814f20

Please sign in to comment.