Skip to content

Commit

Permalink
(rector) process
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesDPC committed Aug 14, 2024
1 parent 07b5d22 commit 596d12e
Show file tree
Hide file tree
Showing 16 changed files with 222 additions and 267 deletions.
43 changes: 16 additions & 27 deletions src/Connector/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,69 +22,58 @@ abstract class Base

/**
* The Mailgun API key or Domain Sending Key (recommended)
* @var string
*/
private static $api_key = '';
private static string $api_key = '';

/**
* The Mailgun sending domain
* @var string
*/
private static $api_domain = '';
private static string $api_domain = '';

/**
* Whether to to enable testmode
* Mailgun will accept the message but will not send it. This is useful for testing purposes.
* You are charged for messages sent in test mode
* @var bool
*/
private static $api_testmode = false;// when true ALL emails are sent with o:testmode = 'yes'

private static bool $api_testmode = false;// when true ALL emails are sent with o:testmode = 'yes'
/**
* Always set the sender header to be the same as the From header
* This assists with removing "on behalf of" in certain email clients
* @var bool
*/
private static $always_set_sender = true;
private static bool $always_set_sender = true;

/**
* Send message via queued job. Values are 'yes', 'no' and 'when-attachments'
* @var string
*/
private static $send_via_job = 'when-attachments';
private static string $send_via_job = 'when-attachments';

/**
* Mailgun requires a "To" header, if none is provided, messages will go to this recipient
* Be aware of the privacy implications of setting this value
* @var string
*/
private static $default_recipient = '';
private static string $default_recipient = '';

/**
* Your webook signing key, provided by Mailgun
* @var string
*/
private static $webhook_signing_key = '';
private static string $webhook_signing_key = '';

/**
* Messages with this variable set will be allowed when a webhook request is made back to the controller
* Messages without this variable will be ignored
* This is useful if you use one mailing domain across multiple sites
* @var string
*/
private static $webhook_filter_variable = '';
private static string $webhook_filter_variable = '';

/**
* Whether webhooks are enabled or not
* @var bool
*/
private static $webhooks_enabled = true;
private static bool $webhooks_enabled = true;

/**
* This is populated in client() and allows tests to check the current API endpoint set
* @var string
*/
private $api_endpoint_url = '';
private string $api_endpoint_url = '';

/**
* Returns an RFC2822 datetime in the format accepted by Mailgun
Expand All @@ -104,6 +93,7 @@ public function getClient($api_key = null)
if (!$api_key) {
$api_key = $this->getApiKey();
}

$api_endpoint = $this->config()->get('api_endpoint_region');
$this->api_endpoint_url = '';
switch ($api_endpoint) {
Expand All @@ -115,6 +105,7 @@ public function getClient($api_key = null)
$client = Mailgun::create($api_key);
break;
}

return $client;
}

Expand All @@ -125,8 +116,7 @@ public function getApiEndpointRegion()

public function getApiKey()
{
$mailgun_api_key = $this->config()->get('api_key');
return $mailgun_api_key;
return $this->config()->get('api_key');
}

public function getWebhookSigningKey()
Expand All @@ -151,14 +141,13 @@ public function getWebhooksEnabled()

public function getApiDomain()
{
$mailgun_api_domain = $this->config()->get('api_domain');
return $mailgun_api_domain;
return $this->config()->get('api_domain');
}

public function isSandbox()
{
$api_domain = $this->getApiDomain();
$result = preg_match("/^sandbox[a-z0-9]+\.mailgun\.org$/i", $api_domain);
$result = preg_match("/^sandbox[a-z0-9]+\.mailgun\.org$/i", (string) $api_domain);
return $result == 1;
}

Expand All @@ -181,7 +170,7 @@ final protected function alwaysSetSender()
/**
* Prior to any send/sendMime action, check config and set testmode if config says so
*/
final protected function applyTestMode(&$parameters)
final protected function applyTestMode(array &$parameters)
{
$mailgun_testmode = $this->config()->get('api_testmode');
if ($mailgun_testmode) {
Expand Down
12 changes: 5 additions & 7 deletions src/Connector/Bounce.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@ class Bounce extends Base
/**
* Remove an address from the bounce suppression list
*/
public function remove($email_address)
public function remove($email_address): ?\Mailgun\Model\Suppression\Bounce\DeleteResponse
{
$valid = Email::is_valid_address($email_address);
if (!$valid) {
throw new Exception("{$email_address} is not a valid email address");
}

$api_key = $this->getApiKey();
$client = Mailgun::create($api_key);
$domain = $this->getApiDomain();
$response = $client->suppressions()->bounces()->delete($domain, $email_address);
return $response;
return $client->suppressions()->bounces()->delete($domain, $email_address);
}

/**
* See: https://documentation.mailgun.com/en/latest/api-suppressions.html#add-a-single-bounce
*/
public function add($email_address, $code = 550, $error = "", $created_at = "")
public function add($email_address, $code = 550, $error = "", $created_at = ""): ?\Mailgun\Model\Suppression\Bounce\CreateResponse
{
$valid = Email::is_valid_address($email_address);
if (!$valid) {
Expand All @@ -57,8 +57,6 @@ public function add($email_address, $code = 550, $error = "", $created_at = "")
$params['created_at'] = $created_at;
}

$response = $client->suppressions()->bounces()->create($domain, $email_address, $params);

return $response;
return $client->suppressions()->bounces()->create($domain, $email_address, $params);
}
}
7 changes: 4 additions & 3 deletions src/Connector/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ class Event extends Base
* @param string $begin an RFC 2822 formatted UTC datetime OR empty string for no begin datetime
* @param string $event_filter see https://documentation.mailgun.com/en/latest/api-events.html#event-types can also be a filter expression e.g "failed OR rejected"
* @param array $extra_params extra parameters for API request
* @return array
*/
public function pollEvents($begin = null, $event_filter = "", $extra_params = [])
public function pollEvents($begin = null, $event_filter = "", $extra_params = []): array
{
$api_key = $this->getApiKey();
$client = Mailgun::create($api_key);
Expand Down Expand Up @@ -60,6 +59,7 @@ public function pollEvents($begin = null, $event_filter = "", $extra_params = []
// recursively retrieve the events based on pagination
$this->getNextPage($client, $response);
}

return $this->results;
}

Expand Down Expand Up @@ -90,8 +90,9 @@ private function getNextPage($client, $response)
$items = $response->getItems();
if (empty($items)) {
// no more items - nothing to do
return;
return null;
}

// add to results
$this->results = array_merge($this->results, $items);
return $this->getNextPage($client, $response);
Expand Down
50 changes: 25 additions & 25 deletions src/Connector/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public function getMime(MailgunEvent $event)
if (empty($event->StorageURL)) {
throw new Exception("No StorageURL found on MailgunEvent #{$event->ID}");
}

// Get the mime encoded message, by passing the Accept header
$message = $client->messages()->show($event->StorageURL, true);
return $message;
Expand Down Expand Up @@ -120,7 +121,6 @@ public function send($parameters)

/**
* Sends a message
* @param array $parameters
*/
protected function sendMessage(array $parameters)
{
Expand Down Expand Up @@ -160,7 +160,7 @@ public function encodeAttachments(&$parameters)
{
if (!empty($parameters['attachment']) && is_array($parameters['attachment'])) {
foreach ($parameters['attachment'] as $k=>$attachment) {
$parameters['attachment'][$k]['fileContent'] = base64_encode($attachment['fileContent']);
$parameters['attachment'][$k]['fileContent'] = base64_encode((string) $attachment['fileContent']);
}
}
}
Expand All @@ -173,7 +173,7 @@ public function decodeAttachments(&$parameters)
{
if (!empty($parameters['attachment']) && is_array($parameters['attachment'])) {
foreach ($parameters['attachment'] as $k=>$attachment) {
$parameters['attachment'][$k]['fileContent'] = base64_decode($attachment['fileContent']);
$parameters['attachment'][$k]['fileContent'] = base64_decode((string) $attachment['fileContent']);
}
}
}
Expand All @@ -185,13 +185,15 @@ public function decodeAttachments(&$parameters)
private function getSendDateTime($in): ?\DateTime
{
try {
$dt = $default = null;
$dt = null;
$default = null;
if ($in > 0) {
$dt = new \DateTime("now +{$in} seconds");
}
} catch (\Exception $e) {
} catch (\Exception) {
}
return $dt ? $dt : $default;

return $dt ?: $default;
}

/**
Expand All @@ -205,13 +207,15 @@ protected function queueAndSend($domain, $parameters, $in)
{
$this->encodeAttachments($parameters);
$startAfter = null;
if ($start = $this->getSendDateTime($in)) {
if (($start = $this->getSendDateTime($in)) instanceof \DateTime) {
$startAfter = $start->format('Y-m-d H:i:s');
}

$job = new SendJob($domain, $parameters);
if ($job_id = QueuedJobService::singleton()->queueJob($job, $startAfter)) {
return QueuedJobDescriptor::get()->byId($job_id);
}

return false;
}

Expand All @@ -231,37 +235,32 @@ public function isDelivered(MailgunEvent $event, $cleanup = true)
$timeframe = 'now -30 days';
$begin = Base::DateTime($timeframe);

$event_filter = MailgunEvent::DELIVERED;
$resubmit = false;// no we don't want to resubmit
$event_filter = MailgunEvent::DELIVERED;// no we don't want to resubmit
$extra_params = [
'limit' => 25,
'message-id' => $event->MessageId,
'recipient' => $event->Recipient,// match against the recipient of the event
];

$events = $connector->pollEvents($begin, $event_filter, $extra_params);

$is_delivered = !empty($events);
return $is_delivered;
return !empty($events);
}

/**
* Trim < and > from message id
* @return string
* @param string $message_id
*/
public static function cleanMessageId($message_id)
public static function cleanMessageId($message_id): string
{
$message_id = trim($message_id, "<>");
return $message_id;
return trim($message_id, "<>");
}

/**
* When sending via a queued job, this the start time of the job in the future (in seconds)
* This is not the "o:deliverytime" option ("Messages can be scheduled for a maximum of 3 days in the future.")
* To set "deliverytime" set it as an option to setOptions()
*/
public function setSendIn(float $seconds)
public function setSendIn(float $seconds): static
{
$this->send_in_seconds = $seconds;
return $this;
Expand All @@ -277,7 +276,7 @@ public function getSendIn()
* and value is a dictionary with variables
* that can be referenced in the message body.
*/
public function setRecipientVariables(array $recipient_variables)
public function setRecipientVariables(array $recipient_variables): static
{
$this->recipient_variables = $recipient_variables;
return $this;
Expand All @@ -291,7 +290,7 @@ public function getRecipientVariables()
return $this->recipient_variables;
}

public function setAmpHtml(string $html)
public function setAmpHtml(string $html): static
{
$this->amp_html = $html;
return $this;
Expand All @@ -302,7 +301,7 @@ public function getAmpHtml()
return $this->amp_html;
}

public function setTemplate($template, $version = "", $include_in_text = "")
public function setTemplate($template, $version = "", $include_in_text = ""): static
{
if ($template) {
$this->template = [
Expand All @@ -311,6 +310,7 @@ public function setTemplate($template, $version = "", $include_in_text = "")
'text' => $include_in_text == "yes" ? "yes" : "",
];
}

return $this;
}

Expand All @@ -322,7 +322,7 @@ public function getTemplate()
/**
* Keys are not prefixed with "o:"
*/
public function setOptions(array $options)
public function setOptions(array $options): static
{
$this->options = $options;
return $this;
Expand All @@ -336,7 +336,7 @@ public function getOptions()
/**
* Keys are not prefixed with "h:"
*/
public function setCustomHeaders(array $headers)
public function setCustomHeaders(array $headers): static
{
$this->headers = $headers;
return $this;
Expand All @@ -350,7 +350,7 @@ public function getCustomHeaders()
/**
* Keys are not prefixed with "v:"
*/
public function setVariables(array $variables)
public function setVariables(array $variables): static
{
$this->variables = $variables;
return $this;
Expand All @@ -363,9 +363,8 @@ public function getVariables()

/**
* Based on options set in {@link NSWDPC\Messaging\Mailgun\MailgunEmail} set Mailgun options, params, headers and variables
* @param array $parameters
*/
protected function addCustomParameters(&$parameters)
protected function addCustomParameters(array &$parameters)
{

// VARIABLES
Expand All @@ -387,6 +386,7 @@ protected function addCustomParameters(&$parameters)
if (!empty($template['version'])) {
$parameters["t:version"] = $template['version'];
}

if (isset($template['text']) && $template['text'] == "yes") {
$parameters["t:text"] = $template['text'];
}
Expand Down
Loading

0 comments on commit 596d12e

Please sign in to comment.