Skip to content

[Notifier] Add MessageMedia Bridge #41375

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

Merged
merged 1 commit into from
Jul 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
use Symfony\Component\Notifier\Bridge\MessageBird\MessageBirdTransport;
use Symfony\Component\Notifier\Bridge\MessageMedia\MessageMediaTransportFactory;
use Symfony\Component\Notifier\Bridge\MicrosoftTeams\MicrosoftTeamsTransportFactory;
use Symfony\Component\Notifier\Bridge\Mobyt\MobytTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
Expand Down Expand Up @@ -2431,6 +2432,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
MattermostTransportFactory::class => 'notifier.transport_factory.mattermost',
MercureTransportFactory::class => 'notifier.transport_factory.mercure',
MessageBirdTransport::class => 'notifier.transport_factory.messagebird',
MessageMediaTransportFactory::class => 'notifier.transport_factory.messagemedia',
MicrosoftTeamsTransportFactory::class => 'notifier.transport_factory.microsoftteams',
MobytTransportFactory::class => 'notifier.transport_factory.mobyt',
NexmoTransportFactory::class => 'notifier.transport_factory.nexmo',
Expand Down Expand Up @@ -2460,6 +2462,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
case 'lightsms': $package = 'light-sms'; break;
case 'linkedin': $package = 'linked-in'; break;
case 'messagebird': $package = 'message-bird'; break;
case 'messagemedia': $package = 'message-media'; break;
case 'microsoftteams': $package = 'microsoft-teams'; break;
case 'ovhcloud': $package = 'ovh-cloud'; break;
case 'rocketchat': $package = 'rocket-chat'; break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
use Symfony\Component\Notifier\Bridge\MessageBird\MessageBirdTransportFactory;
use Symfony\Component\Notifier\Bridge\MessageMedia\MessageMediaTransportFactory;
use Symfony\Component\Notifier\Bridge\MicrosoftTeams\MicrosoftTeamsTransportFactory;
use Symfony\Component\Notifier\Bridge\Mobyt\MobytTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
Expand Down Expand Up @@ -191,6 +192,10 @@
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')

->set('notifier.transport_factory.messagemedia', MessageMediaTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')

->set('notifier.transport_factory.telnyx', TelnyxTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.4
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/MessageMedia/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2021 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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

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

namespace Symfony\Component\Notifier\Bridge\MessageMedia;

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\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Adrian Nguyen <vuphuong87@gmail.com>
*/
final class MessageMediaTransport extends AbstractTransport
{
protected const HOST = 'api.messagemedia.com';

private $apiKey;
private $apiSecret;
private $from;

public function __construct(string $apiKey, string $apiSecret, string $from = null, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
$this->apiKey = $apiKey;
$this->apiSecret = $apiSecret;
$this->from = $from;

parent::__construct($client, $dispatcher);
}

public function __toString(): string
{
if (null !== $this->from) {
return sprintf('messagemedia://%s?from=%s', $this->getEndpoint(), $this->from);
}

return sprintf('messagemedia://%s', $this->getEndpoint());
}

public function supports(MessageInterface $message): bool
{
return $message instanceof SmsMessage;
}

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

$endpoint = sprintf('https://%s/v1/messages', $this->getEndpoint());
$response = $this->client->request(
'POST',
$endpoint,
[
'auth_basic' => $this->apiKey.':'.$this->apiSecret,
'json' => [
'messages' => [
[
'destination_number' => $message->getPhone(),
'source_number' => $this->from,
'content' => $message->getSubject(),
],
],
],
]
);

if (202 === $response->getStatusCode()) {
$result = $response->toArray(false)['messages'][0];
$sentMessage = new SentMessage($message, (string) $this);
$sentMessage->setMessageId($result['message_id']);

return $sentMessage;
}

try {
$error = $response->toArray(false);

$errorMessage = $error['details'][0] ?? ($error['message'] ?? 'Unknown reason');
} catch (DecodingExceptionInterface | TransportExceptionInterface $e) {
$errorMessage = 'Unknown reason';
}

throw new TransportException(sprintf('Unable to send the SMS: "%s".', $errorMessage), $response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

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

namespace Symfony\Component\Notifier\Bridge\MessageMedia;

use Symfony\Component\Notifier\Exception\UnsupportedSchemeException;
use Symfony\Component\Notifier\Transport\AbstractTransportFactory;
use Symfony\Component\Notifier\Transport\Dsn;
use Symfony\Component\Notifier\Transport\TransportInterface;

/**
* @author Adrian Nguyen <vuphuong87@gmail.com>
*/
final class MessageMediaTransportFactory extends AbstractTransportFactory
{
/**
* @return MessageMediaTransport
*/
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();

if ('messagemedia' !== $scheme) {
throw new UnsupportedSchemeException($dsn, 'messagemedia', $this->getSupportedSchemes());
}

$apiKey = $this->getUser($dsn);
$apiSecret = $this->getPassword($dsn);
$from = $dsn->getOption('from');
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();

return (new MessageMediaTransport($apiKey, $apiSecret, $from, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}

protected function getSupportedSchemes(): array
{
return ['messagemedia'];
}
}
25 changes: 25 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/MessageMedia/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
MessageMedia Notifier
=================

Provides [MessageMedia](https://messagemedia.com/) integration for Symfony Notifier.

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

```
MESSAGEMEDIA_DSN=messagemedia://API_KEY:API_SECRET@default?from=FROM
```

where:
- `API_KEY` is your API key
- `API_SECRET` is your API secret
- `FROM` is your registered sender ID (optional). Accepted values: 3-15 letters, could be alpha tag, shortcode or international phone number.
When phone number starts with a `+` sign, it needs to be url encoded in the DSN

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)
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

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

namespace Symfony\Component\Notifier\Bridge\MessageMedia\Tests;

use Symfony\Component\Notifier\Bridge\MessageMedia\MessageMediaTransportFactory;
use Symfony\Component\Notifier\Test\TransportFactoryTestCase;
use Symfony\Component\Notifier\Transport\TransportFactoryInterface;

final class MessageMediaTransportFactoryTest extends TransportFactoryTestCase
{
/**
* @return MessageMediaTransportFactory
*/
public function createFactory(): TransportFactoryInterface
{
return new MessageMediaTransportFactory();
}

public function createProvider(): iterable
{
yield [
'messagemedia://host.test',
'messagemedia://apiKey:apiSecret@host.test',
];

yield [
'messagemedia://host.test?from=TEST',
'messagemedia://apiKey:apiSecret@host.test?from=TEST',
];
}

public function supportsProvider(): iterable
{
yield [true, 'messagemedia://apiKey:apiSecret@default'];
yield [false, 'somethingElse://apiKey:apiSecret@default'];
}

public function unsupportedSchemeProvider(): iterable
{
yield ['somethingElse://apiKey:apiSecret@default'];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

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

namespace Symfony\Component\Notifier\Bridge\MessageMedia\Tests;

use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\Notifier\Bridge\MessageMedia\MessageMediaTransport;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Exception\TransportExceptionInterface;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Test\TransportTestCase;
use Symfony\Component\Notifier\Transport\TransportInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

final class MessageMediaTransportTest extends TransportTestCase
{
/**
* @return MessageMediaTransport
*/
public function createTransport(HttpClientInterface $client = null, string $from = null): TransportInterface
{
return new MessageMediaTransport('apiKey', 'apiSecret', $from, $client ?? $this->createMock(HttpClientInterface::class));
}

public function toStringProvider(): iterable
{
yield ['messagemedia://api.messagemedia.com', $this->createTransport()];
yield ['messagemedia://api.messagemedia.com?from=TEST', $this->createTransport(null, 'TEST')];
}

public function supportedMessagesProvider(): iterable
{
yield [new SmsMessage('0491570156', 'Hello!')];
}

public function unsupportedMessagesProvider(): iterable
{
yield [new ChatMessage('Hello!')];
yield [$this->createMock(MessageInterface::class)];
}

/**
* @dataProvider exceptionIsThrownWhenHttpSendFailedProvider
*
* @throws TransportExceptionInterface
*/
public function testExceptionIsThrownWhenHttpSendFailed(int $statusCode, string $content, string $expectedExceptionMessage)
{
$response = $this->createMock(ResponseInterface::class);
$response->method('getStatusCode')
->willReturn($statusCode);
$response->method('getContent')
->willReturn($content);

$client = new MockHttpClient($response);

$transport = new MessageMediaTransport('apiKey', 'apiSecret', null, $client);
$this->expectException(TransportException::class);
$this->expectExceptionMessage($expectedExceptionMessage);

$transport->send(new SmsMessage('+61491570156', 'Hello!'));
}

public function exceptionIsThrownWhenHttpSendFailedProvider(): iterable
{
yield [503, '', 'Unable to send the SMS: "Unknown reason".'];
yield [500, '{"details": ["Something went wrong."]}', 'Unable to send the SMS: "Something went wrong.".'];
yield [403, '{"message": "Forbidden."}', 'Unable to send the SMS: "Forbidden.'];
yield [401, '{"Unauthenticated"}', 'Unable to send the SMS: "Unknown reason".'];
}
}
Loading