Skip to content

Commit

Permalink
Add Sweego Notifier bridge
Browse files Browse the repository at this point in the history
  • Loading branch information
welcoMattic committed Oct 17, 2024
1 parent 2d1fe22 commit 34e8a96
Show file tree
Hide file tree
Showing 22 changed files with 662 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2881,6 +2881,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
NotifierBridge\SmsSluzba\SmsSluzbaTransportFactory::class => 'notifier.transport_factory.sms-sluzba',
NotifierBridge\Smsense\SmsenseTransportFactory::class => 'notifier.transport_factory.smsense',
NotifierBridge\SpotHit\SpotHitTransportFactory::class => 'notifier.transport_factory.spot-hit',
NotifierBridge\Sweego\SweegoTransportFactory::class => 'notifier.transport_factory.sweego',
NotifierBridge\Telegram\TelegramTransportFactory::class => 'notifier.transport_factory.telegram',
NotifierBridge\Telnyx\TelnyxTransportFactory::class => 'notifier.transport_factory.telnyx',
NotifierBridge\Termii\TermiiTransportFactory::class => 'notifier.transport_factory.termii',
Expand Down Expand Up @@ -2948,6 +2949,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
$loader->load('notifier_webhook.php');

$webhookRequestParsers = [
NotifierBridge\Sweego\Webhook\SweegoRequestParser::class => 'notifier.webhook.request_parser.sweego',
NotifierBridge\Twilio\Webhook\TwilioRequestParser::class => 'notifier.webhook.request_parser.twilio',
NotifierBridge\Vonage\Webhook\VonageRequestParser::class => 'notifier.webhook.request_parser.vonage',
];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
'smsense' => Bridge\Smsense\SmsenseTransportFactory::class,
'smsmode' => Bridge\Smsmode\SmsmodeTransportFactory::class,
'spot-hit' => Bridge\SpotHit\SpotHitTransportFactory::class,
'sweego' => Bridge\Sweego\SweegoTransportFactory::class,
'telnyx' => Bridge\Telnyx\TelnyxTransportFactory::class,
'termii' => Bridge\Termii\TermiiTransportFactory::class,
'turbo-sms' => Bridge\TurboSms\TurboSmsTransportFactory::class,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\Notifier\Bridge\Sweego\Webhook\SweegoRequestParser;
use Symfony\Component\Notifier\Bridge\Twilio\Webhook\TwilioRequestParser;
use Symfony\Component\Notifier\Bridge\Vonage\Webhook\VonageRequestParser;

return static function (ContainerConfigurator $container) {
$container->services()
->set('notifier.webhook.request_parser.sweego', SweegoRequestParser::class)
->alias(SweegoRequestParser::class, 'notifier.webhook.request_parser.sweego')

->set('notifier.webhook.request_parser.twilio', TwilioRequestParser::class)
->alias(TwilioRequestParser::class, 'notifier.webhook.request_parser.twilio')

Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
7 changes: 7 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.2
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024-present Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
53 changes: 53 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
Sweego Notifier
===============

Provides [Sweego](https://www.sweego.io/) integration for Symfony Notifier.

DSN example
-----------

```
SWEEGO_DSN=sweego://API_KEY@default?region=REGION&campaign_type=CAMPAIGN_TYPE&bat=BAT&campaign_id=CAMPAIGN_ID&shorten_urls=SHORTEN_URLS&shorten_with_protocol=SHORTEN_WITH_PROTOCOL
```

where:
- `API_KEY` (required) is your Sweego API key
- `REGION` (required) is the region of the phone number (e.g. `FR`, ISO 3166-1 alpha-2 country code)
- `CAMPAIGN_TYPE` (required) is the type of the campaign (e.g. `transac`)
- `BAT` (optional) is the test mode (e.g. `true`)
- `CAMPAIGN_ID` (optional) is the campaign id (e.g. `string`)
- `SHORTEN_URLS` (optional) is the shorten urls option (e.g. `true`)
- `SHORTEN_WITH_PROTOCOL` (optional) is the shorten with protocol option (e.g. `true`)

Advanced Message options
------------------------

```php
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Bridge\Sweego\SweegoOptions;

$sms = new SmsMessage('+1411111111', 'My message');

$options = (new SweegoOptions())
// False by default, set 'bat' to true enable test mode (no sms sent, only for testing purpose)
->bat(true)
// Optional, used for tracking / filtering purpose on our platform; identity an SMS campaign and allow to see logs / stats only for this campaign
->campaignId('string')
// True by default, we replace all url in the SMS content by a shortened url version (reduce the characters of the sms)
->shortenUrls(true)
// True by default, add scheme to shortened url version
->shortenWithProtocol(true);

// Add the custom options to the sms message and send the message
$sms->options($options);

$texter->send($sms);
```

Resources
---------

* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
67 changes: 67 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/SweegoOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Bridge\Sweego;

use Symfony\Component\Notifier\Message\MessageOptionsInterface;

class SweegoOptions implements MessageOptionsInterface
{
public const REGION = 'region';
public const BAT = 'bat';
public const CAMPAIGN_TYPE = 'campaign_type';
public const CAMPAIGN_ID = 'campaign_id';
public const SHORTEN_URLS = 'shorten_urls';
public const SHORTEN_WITH_PROTOCOL = 'shorten_with_protocol';

public function __construct(
private array $options = [],
) {
}

public function toArray(): array
{
return $this->options;
}

public function getRecipientId(): ?string
{
return null;
}

public function bat(bool $bat): self
{
$this->options[self::BAT] = $bat;

return $this;
}

public function campaignId(string $campaignId): self
{
$this->options[self::CAMPAIGN_ID] = $campaignId;

return $this;
}

public function shortenUrls(bool $shortenUrls): self
{
$this->options[self::SHORTEN_URLS] = $shortenUrls;

return $this;
}

public function shortenWithProtocol(bool $shortenWithProtocol): self
{
$this->options[self::SHORTEN_WITH_PROTOCOL] = $shortenWithProtocol;

return $this;
}
}
157 changes: 157 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Sweego/SweegoTransport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Bridge\Sweego;

use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SentMessage;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Transport\AbstractTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Mathieu Santostefano <[email protected]>
*/
final class SweegoTransport extends AbstractTransport
{
protected const HOST = 'api.sweego.io';

public function __construct(
#[\SensitiveParameter] private readonly string $apiKey,
private readonly string $region,
private readonly string $campaignType,
private readonly ?bool $bat,
private readonly ?string $campaignId,
private readonly ?bool $shortenUrls,
private readonly ?bool $shortenWithProtocol,
?HttpClientInterface $client = null,
?EventDispatcherInterface $dispatcher = null,
) {
parent::__construct($client, $dispatcher);
}

public function __toString(): string
{
return \sprintf('sweego://%s%s', $this->getEndpoint(), '?'.http_build_query([
SweegoOptions::REGION => $this->region,
SweegoOptions::CAMPAIGN_TYPE => $this->campaignType,
SweegoOptions::BAT => $this->bat,
SweegoOptions::CAMPAIGN_ID => $this->campaignId,
SweegoOptions::SHORTEN_URLS => $this->shortenUrls,
SweegoOptions::SHORTEN_WITH_PROTOCOL => $this->shortenWithProtocol,
]));
}

public function supports(MessageInterface $message): bool
{
return $message instanceof SmsMessage
&& (null === $message->getOptions() || $message->getOptions() instanceof SweegoOptions);
}

protected function doSend(MessageInterface $message): SentMessage
{
if (!$message instanceof SmsMessage) {
throw new UnsupportedMessageTypeException(__CLASS__, SmsMessage::class, $message);
}

$options = $message->getOptions()?->toArray() ?? [];

$body = [
'recipients' => [
[
'num' => $message->getPhone(),
'region' => $options[SweegoOptions::REGION] ?? $this->region,
],
],
'message-txt' => $message->getSubject(),
'channel' => 'sms',
'provider' => 'sweego',
];

$body = $this->setBat($body, $options);
$body = $this->setCampaignType($body, $options);
$body = $this->setCampaignId($body, $options);
$body = $this->setShortenUrls($body, $options);
$body = $this->setShortenWithProtocol($body, $options);

$endpoint = \sprintf('https://%s/send', $this->getEndpoint());
$response = $this->client->request('POST', $endpoint, [
'headers' => [
'Api-Key' => $this->apiKey,
],
'json' => array_filter($body),
]);

try {
$statusCode = $response->getStatusCode();
} catch (TransportExceptionInterface $e) {
throw new TransportException('Could not reach the remote Sweego server.', $response, 0, $e);
}

if (200 !== $statusCode) {
throw new TransportException('Unable to send the SMS.', $response);
}

$success = $response->toArray(false);

$sentMessage = new SentMessage($message, (string) $this);
$sentMessage->setMessageId(array_values($success['swg_uids'])[0]);

return $sentMessage;
}

private function setBat(array $body, array $options): array
{
$body['bat'] = (bool) ($options[SweegoOptions::BAT] ?? $this->bat);

return $body;
}

private function setCampaignType(array $body, array $options): array
{
$body['campaign-type'] = $this->campaignType;

if (!\array_key_exists(SweegoOptions::CAMPAIGN_TYPE, $options) && \is_string($options[SweegoOptions::CAMPAIGN_TYPE])) {
$body['campaign-type'] = $options[SweegoOptions::CAMPAIGN_TYPE];
}

return $body;
}

private function setCampaignId(array $body, array $options): array
{
$body['campaign-id'] = $this->campaignId;

if (!\array_key_exists(SweegoOptions::CAMPAIGN_ID, $options) && \is_string($options[SweegoOptions::CAMPAIGN_ID])) {
$body['campaign-id'] = $options[SweegoOptions::CAMPAIGN_ID];
}

return $body;
}

private function setShortenUrls(array $body, array $options): array
{
$body['shorten_urls'] = (bool) ($options[SweegoOptions::SHORTEN_URLS] ?? $this->shortenUrls);

return $body;
}

private function setShortenWithProtocol(array $body, array $options): array
{
$body['shorten_with_protocol'] = (bool) ($options[SweegoOptions::SHORTEN_WITH_PROTOCOL] ?? $this->shortenWithProtocol);

return $body;
}
}
Loading

0 comments on commit 34e8a96

Please sign in to comment.