feature #40607 [Notifier] Add LightSms notifier bridge (Vasilij Dusko, StaffNowa)

This PR was merged into the 5.3-dev branch.

Discussion
----------

[Notifier] Add LightSms notifier bridge

| Q             | A
| ------------- | ---
| Branch?       | 5.x
| Bug fix?      | no
| New feature?  | yes <!-- please update src/**/CHANGELOG.md files -->
| Deprecations? | no <!-- please update UPGRADE-*.md and src/**/CHANGELOG.md files -->
| License       | MIT
| Doc PR        | symfony/symfony-docs/pull/15178
| Recipe PR | https://github.com/symfony/recipes/pull/921

LightSms notifier https://github.com/D4DLab/lightsms-notifier

Commits
-------

37c665eb5c * LightSmsTransport.php - make fabbot happy
68a12fa4f4 * fix tests
f1f83b9e5c * LightSmsTransport.php - use query string parameters
026dcd97a9 * LightSmsTransport.php - isset
2a9ac2d92a * LightSmsTransport.php - fix
4213564be1 * composer.json - fix Fabien comment from another pull request #40646
21e972a69e * coding standard
bea5256cc2 * type cast. On success lightsms return error code like string. On error return integer.
9b2e2d0b4a * type cast. On success lightsms return error code like string. On error return integer.
0d7488b10a * type cast. On success lightsms return error code like string. On error return integer.
9a832ef595 * LightSmsTransport.php - via mistake removed www which return (Closing direction to the user). Removed additional isset which in reality not needed. Added new method which allow to return "unknown error" and throw exception if not successfully
178d9c2a5a * pull request #40696
95e82f6ef1 Update LightSmsTransport.php
a197deeed1 * LightSmsTransport.php - better to remove if we do not have it?
83d259832b * Coding Standard patch
1ff97e410a * LightSmsTransport.php - build signature and use http_build_query, timestamp int
1c993b7224 * ERROR_CODES -> int * www. - bug * isset validate ['error']
1b59a7d47e * LightSmsTransport.php - string param
58ac708d0f * LightSmsTransport.php - return back www (without will not work). Now fail tests
b9f9ff8c94 * LightSmsTransport.php - tests fail
265f776394 * LightSmsTransport.php - issue with Symfony\Component\Notifier\Bridge\LightSms\Tests\LightSmsTransportTest
23a446a2e1 * LightSmsTransport.php - issue with Symfony\Component\Notifier\Bridge\LightSms\Tests\LightSmsTransportTest
08235e5a3c * LightSmsTransport.php - bug fix
80ef5ba565 * LightSmsTransport.php - Unable to send the SMS: Closing direction to the user
08b0729751 Update LightSmsTransport.php
7180c1f400 Update LightSmsTransport.php
f16b4d2aa2 * phone changed to from
7f13dbf711 * sender changed to from
e20ef1ed35 * LightSmsTransport.php - change + to 00
b0e64b9250 * LightSmsTransport.php - not ok throw exception
fc13bb27e2 * LightSmsTransport.php - changed login for validation (the same like we have all places)
5d2e6928f3 * LightSmsTransport.php - escape phone number
8620e828a7 * LightSmsTransport.php - move timestamp
66c34baf03 Update README.md
2e0e1d733d Update README.md
7b51e0dd7f Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
079406ed3d Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
0e41bc9186 Update src/Symfony/Component/Notifier/Bridge/LightSms/Tests/LightSmsTransportFactoryTest.php
3d0d79cfe2 Update src/Symfony/Component/Notifier/Bridge/LightSms/Tests/LightSmsTransportFactoryTest.php
e0a68bd0ac Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
1b073c2366 Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
b0891be0b2 Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
49b4780f40 Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
b2e46387b7 Update src/Symfony/Component/Notifier/Bridge/LightSms/LightSmsTransport.php
c02dbbd963 Update src/Symfony/Component/Notifier/Bridge/LightSms/README.md
9f89014d94 Update src/Symfony/Component/Notifier/Bridge/LightSms/README.md
5e54dfe475 * LightSmsTransport.php - quick fix for private constant.
3cbbc85e43 * HOST split into two parts
9e1809e6ae * small changes
febff4613d Update src/Symfony/Component/Notifier/Bridge/LightSms/LICENSE
4a11b945a3 * github account author
728a3e2450 * Transport.php - missing use
ce41756a6c * notifier_transports.php - Coding Standard
d1ccd46e75 * Attached file changes which are required to run the lightsms notifier
a0fae7dc4a * tests
15686c0851 * LightSmsTransport.php - Coding Standard
2f65b92cba * LightSmsTransport.php - Coding Standard
6792535a52 * composer.json - requirements bug fix
167f325f40 * LightSmsTransport.php - logic error
be8f994fca * LightSmsTransport.php - return type
f2ba226b46 * LightSmsTransport.php - bug fix
b075c0eae2 * LightSms notifier
This commit is contained in:
Oskar Stark 2021-04-06 12:32:50 +02:00
commit 71a407da29
13 changed files with 446 additions and 0 deletions

View File

@ -23,6 +23,7 @@ use Symfony\Component\Notifier\Bridge\Gitter\GitterTransportFactory;
use Symfony\Component\Notifier\Bridge\GoogleChat\GoogleChatTransportFactory;
use Symfony\Component\Notifier\Bridge\Infobip\InfobipTransportFactory;
use Symfony\Component\Notifier\Bridge\Iqsms\IqsmsTransportFactory;
use Symfony\Component\Notifier\Bridge\LightSms\LightSmsTransportFactory;
use Symfony\Component\Notifier\Bridge\LinkedIn\LinkedInTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
@ -164,5 +165,9 @@ return static function (ContainerConfigurator $container) {
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')
->tag('texter.transport_factory')
->set('notifier.transport_factory.lightsms', LightSmsTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')
;
};

View File

@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore

View File

@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml

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,179 @@
<?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\LightSms;
use Symfony\Component\HttpFoundation\Response;
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 Vasilij Duško <vasilij@prado.lt>
*/
final class LightSmsTransport extends AbstractTransport
{
protected const HOST = 'www.lightsms.com';
private $login;
private $password;
private $from;
private const ERROR_CODES = [
1 => 'Missing Signature',
2 => 'Login not specified',
3 => 'Text not specified',
4 => 'Phone number not specified',
5 => 'Sender not specified',
6 => 'Invalid signature',
7 => 'Invalid login',
8 => 'Invalid sender name',
9 => 'Sender name not registered',
10 => 'Sender name not approved',
11 => 'There are forbidden words in the text',
12 => 'Error in SMS sending',
13 => 'Phone number is in the blackist. SMS sending to this number is forbidden.',
14 => 'There are more than 50 numbers in the request',
15 => 'List not specified',
16 => 'Invalid phone number',
17 => 'SMS ID not specified',
18 => 'Status not obtained',
19 => 'Empty response',
20 => 'The number already exists',
21 => 'No name',
22 => 'Template already exists',
23 => 'Missing Month (Format: YYYY-MM)',
24 => 'Timestamp not specified',
25 => 'Error in access to the list',
26 => 'There are no numbers in the list',
27 => 'No valid numbers',
28 => 'Missing start date (Format: YYYY-MM-DD)',
29 => 'Missing end date (Format: YYYY-MM-DD)',
30 => 'No date (format: YYYY-MM-DD)',
31 => 'Closing direction to the user',
32 => 'Not enough money',
33 => 'Missing phone number',
34 => 'Phone is in stop list',
35 => 'Not enough money',
36 => 'Can not obtain information about phone',
37 => 'Base Id is not set',
38 => 'Phone number already exists in this database',
39 => 'Phone number does not exist in this database',
999 => 'Unknown Error',
];
public function __construct(string $login, string $password, string $from, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
$this->login = $login;
$this->password = $password;
$this->from = $from;
parent::__construct($client, $dispatcher);
}
public function __toString(): string
{
return sprintf('lightsms://%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);
}
$timestamp = time();
$data = [
'login' => $this->login,
'phone' => $this->escapePhoneNumber($message->getPhone()),
'text' => $message->getSubject(),
'sender' => $this->from,
'timestamp' => $timestamp,
];
$data['signature'] = $this->generateSignature($data, $timestamp);
$endpoint = sprintf('https://%s/external/get/send.php', $this->getEndpoint());
$response = $this->client->request(
'GET',
$endpoint,
[
'query' => $data,
]
);
if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new TransportException('Unable to send the SMS.', $response);
}
$content = $response->toArray(false);
// it happens if the host without www
if (isset($content['']['error'])) {
throw new TransportException('Unable to send the SMS: '.$this->getErrorMsg((int) $content['']['error']), $response);
}
if (isset($content['error'])) {
throw new TransportException('Unable to send the SMS: '.$this->getErrorMsg((int) $content['error']), $response);
}
$phone = $this->escapePhoneNumber($message->getPhone());
if (32 === (int) $content[$phone]['error']) {
throw new TransportException('Unable to send the SMS: '.$this->getErrorMsg((int) $content[$phone]['error']), $response);
}
if (0 === (int) $content[$phone]['error']) {
$sentMessage = new SentMessage($message, (string) $this);
if (isset($content[$phone]['id_sms'])) {
$sentMessage->setMessageId($content[$phone]['id_sms']);
}
return $sentMessage;
}
throw new TransportException('Unable to send the SMS.', $response);
}
private function generateSignature(array $data, int $timestamp): string
{
$params = [
'timestamp' => $timestamp,
'login' => $this->login,
'phone' => $data['phone'],
'sender' => $this->from,
'text' => $data['text'],
];
ksort($params);
reset($params);
return md5(implode('', $params).$this->password);
}
private function escapePhoneNumber(string $phoneNumber): string
{
return str_replace('+', '00', $phoneNumber);
}
private function getErrorMsg(int $errorCode): string
{
return self::ERROR_CODES[$errorCode] ?? self::ERROR_CODES[999];
}
}

View File

@ -0,0 +1,49 @@
<?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\LightSms;
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 Vasilij Duško <vasilij@prado.lt>
*/
final class LightSmsTransportFactory extends AbstractTransportFactory
{
/**
* @return LightSmsTransport
*/
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();
if ('lightsms' !== $scheme) {
throw new UnsupportedSchemeException($dsn, 'lightsms', $this->getSupportedSchemes());
}
$login = $this->getUser($dsn);
$token = $this->getPassword($dsn);
$from = $dsn->getRequiredOption('from');
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();
return (new LightSmsTransport($login, $token, $from, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}
protected function getSupportedSchemes(): array
{
return ['lightsms'];
}
}

View File

@ -0,0 +1,26 @@
LightSms Notifier
=================
Provides [LightSms](https://www.lightsms.com/) integration for Symfony Notifier.
DSN example
-----------
```
LIGHTSMS_DSN=lightsms://LOGIN:TOKEN@default?from=PHONE
```
where:
- `LOGIN` is your LightSms login
- `TOKEN` is the token displayed in your account
- `PHONE` is your LightSms sender phone number
See your account info at https://www.lightsms.com/external/client/api/
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,47 @@
<?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\LightSms\Tests;
use Symfony\Component\Notifier\Bridge\LightSms\LightSmsTransportFactory;
use Symfony\Component\Notifier\Test\TransportFactoryTestCase;
use Symfony\Component\Notifier\Transport\TransportFactoryInterface;
final class LightSmsTransportFactoryTest extends TransportFactoryTestCase
{
/**
* @return LightSmsTransportFactory
*/
public function createFactory(): TransportFactoryInterface
{
return new LightSmsTransportFactory();
}
public function createProvider(): iterable
{
yield [
'lightsms://host.test?from=0611223344',
'lightsms://login:token@host.test?from=0611223344',
];
}
public function supportsProvider(): iterable
{
yield [true, 'lightsms://login:token@default?from=37061234567'];
yield [false, 'somethingElse://login:token@default?from=37061234567'];
}
public function unsupportedSchemeProvider(): iterable
{
yield ['somethingElse://login:token@default?from=37061234567'];
yield ['somethingElse://login:token@default']; // missing "from" option
}
}

View File

@ -0,0 +1,47 @@
<?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\LightSms\Tests;
use Symfony\Component\Notifier\Bridge\LightSms\LightSmsTransport;
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;
final class LightSmsTransportTest extends TransportTestCase
{
/**
* @return LightSmsTransport
*/
public function createTransport(?HttpClientInterface $client = null): TransportInterface
{
return new LightSmsTransport('accountSid', 'authToken', 'from', $client ?: $this->createMock(HttpClientInterface::class));
}
public function toStringProvider(): iterable
{
yield ['lightsms://www.lightsms.com?from=from', $this->createTransport()];
}
public function supportedMessagesProvider(): iterable
{
yield [new SmsMessage('0611223344', 'Hello!')];
}
public function unsupportedMessagesProvider(): iterable
{
yield [new ChatMessage('Hello!')];
yield [$this->createMock(MessageInterface::class)];
}
}

View File

@ -0,0 +1,30 @@
{
"name": "symfony/lightsms-notifier",
"type": "symfony-bridge",
"description": "Symfony LightSms Notifier Bridge",
"keywords": ["sms", "light-sms", "notifier"],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Vasilij Duško",
"email": "vasilij@prado.lt"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=7.2.5",
"symfony/http-client": "^4.4|^5.2",
"symfony/notifier": "^5.3"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Notifier\\Bridge\\LightSms\\": "" },
"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 LightSms 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

@ -120,6 +120,10 @@ class UnsupportedSchemeException extends LogicException
'class' => Bridge\Clickatell\ClickatellTransportFactory::class,
'package' => 'symfony/clickatell-notifier',
],
'lightsms' => [
'class' => Bridge\LightSms\LightSmsTransportFactory::class,
'package' => 'symfony/lightsms-notifier',
],
];
/**

View File

@ -21,6 +21,7 @@ use Symfony\Component\Notifier\Bridge\GatewayApi\GatewayApiTransportFactory;
use Symfony\Component\Notifier\Bridge\Gitter\GitterTransportFactory;
use Symfony\Component\Notifier\Bridge\Infobip\InfobipTransportFactory;
use Symfony\Component\Notifier\Bridge\Iqsms\IqsmsTransportFactory;
use Symfony\Component\Notifier\Bridge\LightSms\LightSmsTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mobyt\MobytTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
@ -74,6 +75,7 @@ class Transport
OctopushTransportFactory::class,
GitterTransportFactory::class,
ClickatellTransportFactory::class,
LightSmsTransportFactory::class,
];
private $factories;