Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: geosms adapter #64

Merged
merged 18 commits into from
Nov 10, 2023
78 changes: 78 additions & 0 deletions src/Utopia/Messaging/Adapters/SMS/GEOSMS.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace Utopia\Messaging\Adapters\SMS;

use Utopia\Messaging\Adapters\SMS as SMSAdapter;
use Utopia\Messaging\Adapters\SMS\GEOSMS\CallingCode;
use Utopia\Messaging\Messages\SMS;

class GEOSMS extends SMSAdapter
{
protected $defaultAdapter;

protected $localAdapters = [];

public function __construct(SMSAdapter $defaultAdapter)
{
$this->defaultAdapter = $defaultAdapter;
}

public function getName(): string
{
return 'GEOSMS';
}

public function getMaxMessagesPerRequest(): int
{
loks0n marked this conversation as resolved.
Show resolved Hide resolved
return PHP_INT_MAX;
}

public function setLocal(string $callingCode, SMSAdapter $adapter): self
{
$this->localAdapters[$callingCode] = $adapter;

return $this;
}

protected function process(SMS $message): string
{
$recipientsByCallingCode = $this->groupRecipientsByCallingCode($message->getTo());
$responses = [];
$errors = [];

foreach ($recipientsByCallingCode as $callingCode => $recipients) {
$adapter = isset($this->localAdapters[$callingCode])
? $this->localAdapters[$callingCode]
: $this->defaultAdapter;

try {
$responses[] = $adapter->send(new SMS(
to: $recipients,
content: $message->getContent(),
from: $message->getFrom(),
attachments: $message->getAttachments()
));
} catch (\Exception $e) {
$errors[] = $e;
}
}

if (count($errors) > 0) {
throw new \Exception('Failed to send SMS to some recipients', 0, $errors[0]);
}

return $responses[0];
}

protected function groupRecipientsByCallingCode(array $recipients): array
{
$result = [];

foreach ($recipients as $recipient) {
$callingCode = CallingCode::fromPhoneNumber($recipient);
$result[$callingCode][] = $recipient;
}

return $result;
}
}
Loading
Loading