diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..cd8eb86e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..f9ff88d2 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,32 @@ +name: PHPUnit tests + +on: + - push + - pull_request + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + php: [7.2, 7.3, 7.4, 8.0] + + name: Tests on PHP ${{ matrix.php }} - ${{ matrix.stability }} + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + tools: composer:v2 + coverage: none + + - name: Install dependencies + run: composer update --prefer-source --no-interaction --no-progress + + - name: Execute tests + run: vendor/bin/phpunit --verbose diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..cb67e9e6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/vendor +build +composer.phar +composer.lock +.DS_Store +.phpunit.result.cache +.idea diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 00000000..6fad5be9 --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,21 @@ +filter: + excluded_paths: [tests/*] + +checks: + php: + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true + +tools: + external_code_coverage: true diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 00000000..0285f179 --- /dev/null +++ b/.styleci.yml @@ -0,0 +1 @@ +preset: laravel diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100755 index 00000000..08c8eb6a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to mstatgr will be documented in this file + +## 1.0.0 - 2022-10-28 + +- initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100755 index 00000000..4da74e3f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..09130363 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) Nikolas Chatzidakis + +> 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. diff --git a/README.md b/README.md index fa8362b7..b718b898 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,108 @@ -# New Notification Channels +# M-Stat.gr notifications channel for Laravel -### Suggesting a new channel -Have a suggestion or working on a new channel? Please create a new issue for that service. +[![Latest Version on Packagist](https://img.shields.io/packagist/v/laravel-notification-channels/mstatgr.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/mstatgr) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/laravel-notification-channels/mstatgr/master.svg?style=flat-square)](https://travis-ci.org/laravel-notification-channels/mstatgr) +[![Quality Score](https://img.shields.io/scrutinizer/g/laravel-notification-channels/mstatgr.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/mstatgr) +[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/laravel-notification-channels/mstatgr/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/mstatgr/?branch=master) +[![Total Downloads](https://img.shields.io/packagist/dt/laravel-notification-channels/mstatgr.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/mstatgr) -### I'm working on a new channel -Please create an issue for it if it does not already exist, then PR you code for review. +This package makes it easy to send notifications using [MstatGr](https://m-stat.gr/) with Laravel 9.x. -## Workflow for new channels +This is where your description should go. Add a little code example so build can understand real quick how the package can be used. Try and limit it to a paragraph or two. -1) Head over to the [skeleton repo](https://github.com/laravel-notification-channels/skeleton) download a ZIP copy. This is important, to ensure you start from a fresh commit history. -2) Use find/replace to replace all of the placeholders with the correct values (package name, author name, email, etc). -3) Implement to logic for the channel & add tests. -4) Fork this repo, add it as a remote and push your new channel to a branch. -5) Submit a new PR against this repo for review. -Take a look at our [FAQ](http://laravel-notification-channels.com/) to see our small list of rules, to provide top-notch notification channels. + +## Contents + +- [Installation](#installation) + - [Setting up the MstatGr service](#setting-up-the-MstatGr-service) +- [Usage](#usage) + - [Available Message methods](#available-message-methods) +- [Changelog](#changelog) +- [Testing](#testing) +- [Security](#security) +- [Contributing](#contributing) +- [Credits](#credits) +- [License](#license) + + +## Installation + +Install via composer + +```bash +composer require laravel-notification-channels/mstatgr +``` + +### Setting up the MstatGr service + +Add in the `services.php` configuration file the following lines + +```php + 'mstat' => [ + 'auth_key' => env('MSTAT_AUTH_KEY', ''), + 'default_from' => env('MSTAT_FROM', ''), + ] +``` + +## Usage + +This is a sample Notification class +```php +content('This is a sample sms.') + ->to(306901234567) + ->from('SENDER'); + } +} + +``` +### Available Message methods + +A list of all available options + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. + +## Testing + +``` bash +$ composer test +``` + +## Security + +If you discover any security related issues, please email nikolas@chatzidakis.eu instead of using the issue tracker. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Credits + +- [Nikolas Chatzidakis](https://github.com/nchatzidakis) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. + diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..08bf3d21 --- /dev/null +++ b/composer.json @@ -0,0 +1,45 @@ +{ + "name": "laravel-notification-channels/mstatgr", + "description": "M-Stat Laravel Notification Channel", + "homepage": "https://github.com/laravel-notification-channels/mstatgr", + "license": "MIT", + "authors": [ + { + "name": "Nikolas Chatzidakis", + "email": "nikolas@chatzidakis.eu", + "role": "Developer" + } + ], + "require": { + "php": "^8.0", + "illuminate/notifications": "~9.0", + "illuminate/support": "~9.0", + "illuminate/config": "~9.0", + "illuminate/database": "~9.0", + "illuminate/http": "~9.0", + "guzzlehttp/guzzle": "^7.5" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "orchestra/testbench": "^7.8", + "phpunit/phpunit": "^9.0" + }, + "autoload": { + "psr-4": { + "NotificationChannels\\MstatGr\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "NotificationChannels\\MstatGr\\Test\\": "tests" + } + }, + "scripts": { + "test": "phpunit", + "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover", + "post-autoload-dump": ["@php ./vendor/bin/testbench package:discover --ansi"] + }, + "config": { + "sort-packages": true + } +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 00000000..12590d9f --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + tests + + + + + src/ + + + + + + + + + + diff --git a/src/Exceptions/AuthKeyIsInvalid.php b/src/Exceptions/AuthKeyIsInvalid.php new file mode 100644 index 00000000..9ecbe532 --- /dev/null +++ b/src/Exceptions/AuthKeyIsInvalid.php @@ -0,0 +1,11 @@ +toMstatGr($notifiable); + $this->client->send($notifiable, $notificationData); + } +} diff --git a/src/MstatGrClient.php b/src/MstatGrClient.php new file mode 100644 index 00000000..a455b3ca --- /dev/null +++ b/src/MstatGrClient.php @@ -0,0 +1,89 @@ + $notificationData->from, + 'to' => $notificationData->to, + 'message' => $notificationData->content, + ]; + + if (! $params['to']) { + $params['to'] = $notifiable->routeNotificationFor('MstatGr'); + } + + $response = $this->handleCall($params); + + $responseBody = $response->body(); + if (str($responseBody)->contains('ERROR: Auth Key is empty.')) { + throw new AuthKeyIsMissing(); + } + + if (str($responseBody)->contains('ERROR: Invalid Auth Key.')) { + throw new AuthKeyIsInvalid(); + } + + if (str($responseBody)->contains('ERROR: Invalid IP access.')) { + throw new IpAddressInvalid(); + } + + if (str($responseBody)->contains('ERROR: Invalid IP access.')) { + throw new IpAddressInvalid(); + } + + if (str($responseBody)->contains('ERROR: id is null.')) { + throw new InvalidParameter('ID is null'); + } + + if (str($responseBody)->contains('ERROR: to is null.')) { + throw new InvalidParameter('To is null'); + } + + if (str($responseBody)->contains('ERROR: text is null.')) { + throw new InvalidParameter('Text is null'); + } + + if (str($responseBody)->contains('ERROR: from is null.')) { + throw new InvalidParameter('From is null'); + } + + if (str($responseBody)->contains('ERROR: insufficient balance.')) { + throw new InsufficientBalance(); + } + + if (! $response->ok()) { + throw new \Exception('An error occurred.'); + } + + $result = explode(';', $responseBody); + + return [ + 'is_successful' => $result[0] === 'OK', + 'credits' => $result[2], + ]; + } + + public function handleCall(array $params) + { + return Http::asForm()->post(self::$endpoint, [ + 'auth_key' => \Config::get('services.mstat.auth_key'), + 'id' => (int) now()->getPreciseTimestamp(), + 'to' => $params['to'], + 'text' => $params['message'], + 'from' => $params['from'], + ]); + } +} diff --git a/src/MstatGrMessage.php b/src/MstatGrMessage.php new file mode 100644 index 00000000..71715dca --- /dev/null +++ b/src/MstatGrMessage.php @@ -0,0 +1,48 @@ +content = $content; + $this->from(\Config::get('services.mstat.default_from', '')); + $this->to = null; + } + + public function content(string $value): self + { + $this->content = $value; + + return $this; + } + + public function from(string $value): self + { + if (is_numeric($value) && str($value)->length() > 15) { + throw new InvalidParameter('From should be up to 15 numerice characters.'); + } + + if (! is_numeric($value) && str($value)->length() > 11) { + throw new InvalidParameter('From should be up to 11 alphanumeric characters.'); + } + + $this->from = $value; + + return $this; + } + + public function to(int $value): self + { + $this->to = $value; + + return $this; + } +} diff --git a/src/MstatGrServiceProvider.php b/src/MstatGrServiceProvider.php new file mode 100644 index 00000000..475c7265 --- /dev/null +++ b/src/MstatGrServiceProvider.php @@ -0,0 +1,22 @@ +assertEquals('this is text', $message->content); + } + + /** @test */ + public function it_returns_correct_from_when_not_provided() + { + Config::set('services.mstat.default_from', 'sender'); + + $message = new MstatGrMessage('this is text'); + $this->assertEquals('sender', $message->from); + } + + /** @test */ + public function it_returns_correct_from_when_provided() + { + Config::set('services.mstat.default_from', 'sender'); + + $message = (new MstatGrMessage('this is text')) + ->from('custom'); + $this->assertEquals('custom', $message->from); + } + + /** @test */ + public function it_returns_exception_for_wrong_sender() + { + Config::set('services.mstat.default_from', 'sender_with_many_chars'); + + $this->assertThrows(function () { + (new MstatGrMessage('this is text')); + }, InvalidParameter::class); + + Config::set('services.mstat.default_from', '12345678901234567890'); + + $this->assertThrows(function () { + (new MstatGrMessage('this is text')); + }, InvalidParameter::class); + } + + /** @test */ + public function it_returns_correct_exceptions_after_send() + { + Http::fake([ + 'https://corpsms-api.m-stat.gr/http/sms.php' => Http::response('test 12', 500), + ]); + + $this->assertThrows(function () { + $message = (new MstatGrMessage('this is text')); + (new MstatGrClient())->send(new User(), $message); + }, \Exception::class); + + Http::fake([ + 'https://corpsms-api.m-stat.gr/http/sms.php' => Http::response('test 12', 200), + ]); + + $this->assertThrows(function () { + $message = (new MstatGrMessage('this is text')); + (new MstatGrClient())->send(new User(), $message); + }, \Exception::class); + } + + /** @test */ + public function it_sends_successfully_sms() + { + Http::fake([ + 'https://corpsms-api.m-stat.gr/http/sms.php' => Http::response("OK;1666991968654732;1\n", 200), + ]); + + $message = (new MstatGrMessage('this is text')); + $response = (new MstatGrClient())->send(new TestUser(), $message); + + $this->assertEquals(1, $response['credits']); + $this->assertEquals(true, $response['is_successful']); + } +} + +class TestUser extends User +{ + use Notifiable; +}