feature #38922 [Notifier] Add notifier for Clickatell (Kevin Auivinet, Kevin Auvinet, ke20)

This PR was squashed before being merged into the 5.3-dev branch.

Discussion
----------

[Notifier] Add notifier for Clickatell

| Q             | A
| ------------- | ---
| Branch?       | 5.x
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| License       | MIT

Add notifier bridge for Clickatell

Commits
-------

c508732e95 [Notifier] Add notifier for Clickatell
This commit is contained in:
Oskar Stark 2021-01-25 17:32:49 +01:00
commit ffc2c1e1da
13 changed files with 374 additions and 0 deletions

View File

@ -104,6 +104,7 @@ use Symfony\Component\Mime\Header\Headers;
use Symfony\Component\Mime\MimeTypeGuesserInterface;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Notifier\Bridge\AllMySms\AllMySmsTransportFactory;
use Symfony\Component\Notifier\Bridge\Clickatell\ClickatellTransportFactory;
use Symfony\Component\Notifier\Bridge\Discord\DiscordTransportFactory;
use Symfony\Component\Notifier\Bridge\Esendex\EsendexTransportFactory;
use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory;
@ -2248,6 +2249,7 @@ class FrameworkExtension extends Extension
OctopushTransportFactory::class => 'notifier.transport_factory.octopush',
MercureTransportFactory::class => 'notifier.transport_factory.mercure',
GitterTransportFactory::class => 'notifier.transport_factory.gitter',
ClickatellTransportFactory::class => 'notifier.transport_factory.clickatell',
];
foreach ($classToServices as $class => $service) {

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use Symfony\Component\Notifier\Bridge\AllMySms\AllMySmsTransportFactory;
use Symfony\Component\Notifier\Bridge\Clickatell\ClickatellTransportFactory;
use Symfony\Component\Notifier\Bridge\Discord\DiscordTransportFactory;
use Symfony\Component\Notifier\Bridge\Esendex\EsendexTransportFactory;
use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory;
@ -145,6 +146,10 @@ return static function (ContainerConfigurator $container) {
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')
->set('notifier.transport_factory.clickatell', ClickatellTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')
->set('notifier.transport_factory.null', NullTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')

View File

@ -0,0 +1,7 @@
CHANGELOG
=========
5.3
---
* Add the bridge

View File

@ -0,0 +1,92 @@
<?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\Clickatell;
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\HttpClientInterface;
/**
* @author Kevin Auvinet <k.auvinet@gmail.com>
*/
final class ClickatellTransport extends AbstractTransport
{
protected const HOST = 'api.clickatell.com';
private $authToken;
private $from;
public function __construct(string $authToken, string $from = null, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
$this->authToken = $authToken;
$this->from = $from;
parent::__construct($client, $dispatcher);
}
public function __toString(): string
{
if (null === $this->from) {
return sprintf('clickatell://%s', $this->getEndpoint());
}
return sprintf('clickatell://%s?from=%s', $this->getEndpoint(), $this->from);
}
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/rest/message', $this->getEndpoint());
$response = $this->client->request('POST', $endpoint, [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$this->authToken,
'Content-Type' => 'application/json',
'X-Version' => 1,
],
'json' => [
'from' => $this->from ?? '',
'to' => [$message->getPhone()],
'text' => $message->getSubject(),
],
]);
if (202 === $response->getStatusCode()) {
$result = $response->toArray();
$sentMessage = new SentMessage($message, (string) $this);
$sentMessage->setMessageId($result['data']['message'][0]['apiMessageId']);
return $sentMessage;
}
$content = $response->toArray(false);
$errorCode = $content['error']['code'] ?? '';
$errorInfo = $content['error']['description'] ?? '';
$errorDocumentation = $content['error']['documentation'] ?? '';
throw new TransportException(sprintf('Unable to send SMS with Clickatell: Error code %d with message "%s" (%s).', $errorCode, $errorInfo, $errorDocumentation), $response);
}
}

View File

@ -0,0 +1,44 @@
<?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\Clickatell;
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 Kevin Auvinet <k.auvinet@gmail.com>
*/
final class ClickatellTransportFactory extends AbstractTransportFactory
{
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();
if ('clickatell' !== $scheme) {
throw new UnsupportedSchemeException($dsn, 'clickatell', $this->getSupportedSchemes());
}
$authToken = $this->getUser($dsn);
$from = $dsn->getOption('from');
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();
return (new ClickatellTransport($authToken, $from, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}
protected function getSupportedSchemes(): array
{
return ['clickatell'];
}
}

View File

@ -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.

View File

@ -0,0 +1,23 @@
Clickatell Notifier
===================
Provides [Clickatell](https://www.clickatell.com) integration for Symfony Notifier.
DSN example
-----------
```
CLICKATELL_DSN=clickatell://ACCESS_TOKEN@default?from=FROM
```
where:
- `ACCESS_TOKEN` is your Clickatell auth access token
- `FROM` is the sender
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)

View File

@ -0,0 +1,43 @@
<?php
namespace Symfony\Component\Notifier\Bridge\Clickatell\Tests;
use Symfony\Component\Notifier\Bridge\Clickatell\ClickatellTransportFactory;
use Symfony\Component\Notifier\Tests\TransportFactoryTestCase;
use Symfony\Component\Notifier\Transport\TransportFactoryInterface;
class ClickatellTransportFactoryTest extends TransportFactoryTestCase
{
/**
* @return ClickatellTransportFactory
*/
public function createFactory(): TransportFactoryInterface
{
return new ClickatellTransportFactory();
}
public function createProvider(): iterable
{
yield [
'clickatell://host.test?from=0611223344',
'clickatell://authtoken@host.test?from=0611223344',
];
}
public function supportsProvider(): iterable
{
yield [true, 'clickatell://authtoken@default?from=0611223344'];
yield [false, 'somethingElse://authtoken@default?from=0611223344'];
}
public function incompleteDsnProvider(): iterable
{
yield 'missing auth token' => ['clickatell://host?from=FROM'];
}
public function unsupportedSchemeProvider(): iterable
{
yield ['somethingElse://authtoken@default?from=FROM'];
yield ['somethingElse://authtoken@default']; // missing "from" option
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Symfony\Component\Notifier\Bridge\Clickatell\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\Notifier\Bridge\Clickatell\ClickatellTransport;
use Symfony\Component\Notifier\Exception\LogicException;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
class ClickatellTransportTest extends TestCase
{
public function testToString()
{
$transport = new ClickatellTransport('authToken', 'fromValue', $this->createMock(HttpClientInterface::class));
$transport->setHost('clickatellHost');
$this->assertSame('clickatell://clickatellHost?from=fromValue', (string) $transport);
}
public function testSupports()
{
$transport = new ClickatellTransport('authToken', 'fromValue', $this->createMock(HttpClientInterface::class));
$this->assertTrue($transport->supports(new SmsMessage('+33612345678', 'testSmsMessage')));
$this->assertFalse($transport->supports($this->createMock(MessageInterface::class)));
}
public function testExceptionIsThrownWhenNonMessageIsSend()
{
$transport = new ClickatellTransport('authToken', 'fromValue', $this->createMock(HttpClientInterface::class));
$this->expectException(LogicException::class);
$transport->send($this->createMock(MessageInterface::class));
}
public function testExceptionIsThrownWhenHttpSendFailed()
{
$response = $this->createMock(ResponseInterface::class);
$response->expects($this->exactly(2))
->method('getStatusCode')
->willReturn(500);
$response->expects($this->once())
->method('getContent')
->willReturn(json_encode([
'error' => [
'code' => 105,
'description' => 'Invalid Account Reference EX0000000',
'documentation' => 'https://documentation-page',
],
]));
$client = new MockHttpClient($response);
$transport = new ClickatellTransport('authToken', 'fromValue', $client);
$this->expectException(TransportException::class);
$this->expectExceptionMessage('Unable to send SMS with Clickatell: Error code 105 with message "Invalid Account Reference EX0000000" (https://documentation-page).');
$transport->send(new SmsMessage('+33612345678', 'testSmsMessage'));
}
}

View File

@ -0,0 +1,37 @@
{
"name": "symfony/clickatell-notifier",
"type": "symfony-bridge",
"description": "Symfony Clickatell Notifier Bridge",
"keywords": ["sms", "clickatell", "notifier"],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
},
{
"name": "Kevin Auvinet",
"email": "k.auvinet@gmail.com"
}
],
"require": {
"php": ">=7.2.5",
"symfony/http-client": "^4.3|^5.0",
"symfony/notifier": "^5.3"
},
"require-dev": {
"symfony/event-dispatcher": "^4.3|^5.0"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Notifier\\Bridge\\Clickatell\\": "" },
"exclude-from-classmap": [
"/Tests/"
]
},
"minimum-stability": "dev"
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1" />
</php>
<testsuites>
<testsuite name="Symfony Clickatell Notifier Bridge Test Suite">
<directory>./Tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./</directory>
<exclude>
<directory>./Resources</directory>
<directory>./Tests</directory>
<directory>./vendor</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@ -108,6 +108,10 @@ class UnsupportedSchemeException extends LogicException
'class' => Bridge\Gitter\GitterTransportFactory::class,
'package' => 'symfony/gitter-notifier',
],
'clickatell' => [
'class' => Bridge\Clickatell\ClickatellTransportFactory::class,
'package' => 'symfony/clickatell-notifier',
],
];
/**

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\Notifier;
use Symfony\Component\Notifier\Bridge\AllMySms\AllMySmsTransportFactory;
use Symfony\Component\Notifier\Bridge\Clickatell\ClickatellTransportFactory;
use Symfony\Component\Notifier\Bridge\Discord\DiscordTransportFactory;
use Symfony\Component\Notifier\Bridge\Esendex\EsendexTransportFactory;
use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory;
@ -72,6 +73,7 @@ class Transport
GatewayApiTransportFactory::class,
OctopushTransportFactory::class,
GitterTransportFactory::class,
ClickatellTransportFactory::class,
];
private $factories;