de.propeace.mailinglistsync/Civi/Mailinglistsync/EventMailingList.php
2025-03-28 19:07:48 +01:00

92 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace Civi\Mailinglistsync;
use Civi\Api4\Contact;
use Civi\Mailinglistsync\Exceptions\MailinglistException;
use CRM_Mailinglistsync_ExtensionUtil as E;
use Civi\Api4\Event;
class EventMailingList extends BaseMailingList {
public const CUSTOM_GROUP_NAME = 'Event_Mailing_List';
public const LOCATION_TYPE = 'Event_Mailing_List_Address';
protected const RELATED_CLASS = Event::class;
protected const RELATED_TYPE = 'event';
protected array $event;
/**
* Returns the related event.
*
* @return array
*/
protected function getEntity(): array {
return $this->event ?? NULL;
}
/**
* Set the related event.
*
* @param array $value
*
* @return void
*/
protected function setEntity(array $value): void {
$this->event = $value;
}
public function getRecipients(): array {
try {
$recipientData = Contact::get()
->addSelect('id', 'first_name', 'last_name', 'email.email', 'Active_Directory.SID')
->addJoin('Email AS email', 'LEFT', ['id', '=', 'email.contact_id'])
->addJoin('Participant AS participant', 'INNER',
['id', '=', 'participant.contact_id'],
['participant.event_id', '=', $this->event['id']],
['participant.status', 'IN', self::getEnabledParticipantStatus()],
)
->addGroupBy('id')
->execute()
->getArrayCopy();
}
catch (\Exception $e) {
throw new MailinglistException(
"Could not get recipients for event with id '{$this->event['id']}': {$e->getMessage()}",
MailinglistException::ERROR_CODE_GET_RECIPIENTS_FAILED
);
}
$recipients = [];
foreach ($recipientData as $recipient) {
try {
$recipients[$recipient['email.email']] = new MailingListRecipient(
sid: $recipient['Active_Directory.SID'],
contact_id: $recipient['id'],
first_name: $recipient['first_name'],
last_name: $recipient['last_name'],
email: $recipient['email.email'],
);
} catch (\Exception $e) {
throw new MailinglistException(
"Could not create recipient object for contact with id '{$recipient['id']}'\n$e",
MailinglistException::ERROR_CODE_GET_RECIPIENTS_FAILED
);
}
}
return $recipients;
}
/**
* Get a list of participants status that are enabled for the mailing list.
*
* @return ?array
*/
public static function getEnabledParticipantStatus(): ?array {
return MailingListSettings::get(E::SHORT_NAME . '_participant_status');
}
}