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

[Notifier] Add Brevo bridge (formerly Sendinblue) #50296

Merged
merged 1 commit into from
Jul 9, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2721,6 +2721,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
NotifierBridge\AllMySms\AllMySmsTransportFactory::class => 'notifier.transport_factory.all-my-sms',
NotifierBridge\AmazonSns\AmazonSnsTransportFactory::class => 'notifier.transport_factory.amazon-sns',
NotifierBridge\Bandwidth\BandwidthTransportFactory::class => 'notifier.transport_factory.bandwidth',
NotifierBridge\Brevo\BrevoTransportFactory::class => 'notifier.transport_factory.brevo',
NotifierBridge\Chatwork\ChatworkTransportFactory::class => 'notifier.transport_factory.chatwork',
NotifierBridge\Clickatell\ClickatellTransportFactory::class => 'notifier.transport_factory.clickatell',
NotifierBridge\ClickSend\ClickSendTransportFactory::class => 'notifier.transport_factory.click-send',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
->abstract()
->args([service('event_dispatcher'), service('http_client')->ignoreOnInvalid()])

->set('notifier.transport_factory.brevo', Bridge\Brevo\BrevoTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')

->set('notifier.transport_factory.slack', Bridge\Slack\SlackTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')
Expand Down Expand Up @@ -279,11 +283,11 @@
->set('notifier.transport_factory.simple-textin', Bridge\SimpleTextin\SimpleTextinTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')

->set('notifier.transport_factory.click-send', Bridge\ClickSend\ClickSendTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')

->set('notifier.transport_factory.smsmode', Bridge\Smsmode\SmsmodeTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')
Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Brevo/.gitattributes
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
3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Brevo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
88 changes: 88 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Brevo/BrevoTransport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?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\Brevo;

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 Pierre Tanguy
*/
final class BrevoTransport extends AbstractTransport
{
protected const HOST = 'api.brevo.com';

public function __construct(
#[\SensitiveParameter] private readonly string $apiKey,
private readonly string $sender,
HttpClientInterface $client = null,
EventDispatcherInterface $dispatcher = null
) {
parent::__construct($client, $dispatcher);
}

public function __toString(): string
{
return sprintf('brevo://%s?sender=%s', $this->getEndpoint(), $this->sender);
}

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);
}

$sender = $message->getFrom() ?: $this->sender;

$response = $this->client->request('POST', 'https://'.$this->getEndpoint().'/v3/transactionalSMS/sms', [
'json' => [
'sender' => $sender,
'recipient' => $message->getPhone(),
'content' => $message->getSubject(),
],
'headers' => [
'api-key' => $this->apiKey,
],
]);

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

if (201 !== $statusCode) {
$error = $response->toArray(false);

throw new TransportException('Unable to send the SMS: '.$error['message'], $response);
}

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

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

return $sentMessage;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?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\Brevo;

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

/**
* @author Pierre Tanguy
*/
final class BrevoTransportFactory extends AbstractTransportFactory
{
public function create(Dsn $dsn): BrevoTransport
{
$scheme = $dsn->getScheme();

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

$apiKey = $this->getUser($dsn);
$sender = $dsn->getRequiredOption('sender');
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();

return (new BrevoTransport($apiKey, $sender, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}

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

6.4
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Brevo/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2023-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.
26 changes: 26 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Brevo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Brevo Notifier
===============

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A note about the renaming can be put here

Provides [Brevo](https://brevo.com) integration for Symfony Notifier.
This bridge was created following the rebranding of Sendinblue.

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

```
BREVO_DSN=brevo://API_KEY@default?sender=SENDER
```

where:
- `API_KEY` is your api key from your Brevo account
- `SENDER` is your sender's phone number

See more info at https://developers.brevo.com/reference/sendtransacsms

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,53 @@
<?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\Brevo\Tests;

use Symfony\Component\Notifier\Bridge\Brevo\BrevoTransportFactory;
use Symfony\Component\Notifier\Test\TransportFactoryTestCase;

final class BrevoTransportFactoryTest extends TransportFactoryTestCase
{
public function createFactory(): BrevoTransportFactory
{
return new BrevoTransportFactory();
}

public static function createProvider(): iterable
{
yield [
'brevo://host.test?sender=0611223344',
'brevo://apiKey@host.test?sender=0611223344',
];
}

public static function supportsProvider(): iterable
{
yield [true, 'brevo://apiKey@default?sender=0611223344'];
yield [false, 'somethingElse://apiKey@default?sender=0611223344'];
}

public static function incompleteDsnProvider(): iterable
{
yield 'missing api_key' => ['brevo://default?sender=0611223344'];
}

public static function missingRequiredOptionProvider(): iterable
{
yield 'missing option: sender' => ['brevo://apiKey@host.test'];
}

public static function unsupportedSchemeProvider(): iterable
{
yield ['somethingElse://apiKey@default?sender=0611223344'];
yield ['somethingElse://apiKey@host']; // missing "sender" option
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?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\Brevo\Tests;

use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\Notifier\Bridge\Brevo\BrevoTransport;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Test\TransportTestCase;
use Symfony\Component\Notifier\Tests\Transport\DummyMessage;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

final class BrevoTransportTest extends TransportTestCase
{
public static function createTransport(HttpClientInterface $client = null): BrevoTransport
{
return (new BrevoTransport('api-key', '0611223344', $client ?? new MockHttpClient()))->setHost('host.test');
}

public static function toStringProvider(): iterable
{
yield ['brevo://host.test?sender=0611223344', self::createTransport()];
}

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

public static function unsupportedMessagesProvider(): iterable
{
yield [new ChatMessage('Hello!')];
yield [new DummyMessage()];
}

public function testSendWithErrorResponseThrowsTransportException()
{
$response = $this->createMock(ResponseInterface::class);
$response->expects($this->exactly(2))
->method('getStatusCode')
->willReturn(400);
$response->expects($this->once())
->method('getContent')
->willReturn(json_encode(['code' => 400, 'message' => 'bad request']));

$client = new MockHttpClient(static fn (): ResponseInterface => $response);

$transport = self::createTransport($client);

$this->expectException(TransportException::class);
$this->expectExceptionMessage('Unable to send the SMS: bad request');

$transport->send(new SmsMessage('phone', 'testMessage'));
}
}
34 changes: 34 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Brevo/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "symfony/brevo-notifier",
"type": "symfony-notifier-bridge",
"description": "Symfony Brevo Notifier Bridge",
"keywords": ["brevo", "notifier"],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Pierre Tanguy",
"homepage": "https://github.com/petanguy"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=8.1",
"symfony/http-client": "^5.4|^6.0",
"symfony/notifier": "^6.4"
},
"require-dev": {
"symfony/event-dispatcher": "^5.4|^6.0"
},
"autoload": {
"psr-4": {"Symfony\\Component\\Notifier\\Bridge\\Brevo\\": ""},
"exclude-from-classmap": [
"/Tests/"
]
},
"minimum-stability": "dev"
}