From aea6d70aa09924446834bec9e559cee7806404aa Mon Sep 17 00:00:00 2001 From: dong lei Date: Fri, 31 Dec 2021 11:27:06 +0800 Subject: [PATCH 1/2] init --- .editorconfig | 15 +++ .gitattributes | 10 ++ .github/workflows/tests.yml | 32 +++++ .gitignore | 6 + .scrutinizer.yml | 21 ++++ .styleci.yml | 1 + CHANGELOG.md | 7 ++ CONTRIBUTING.md | 55 ++++++++ LICENSE.md | 21 ++++ README.md | 132 ++++++++++++++++++-- composer.json | 52 ++++++++ phpunit.xml.dist | 29 +++++ src/Exceptions/CouldNotSendNotification.php | 27 ++++ src/WXWorkChannel.php | 85 +++++++++++++ src/WXWorkMessage.php | 64 ++++++++++ tests/ChannelTest.php | 78 ++++++++++++ tests/MessageTest.php | 41 ++++++ 17 files changed, 664 insertions(+), 12 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 .scrutinizer.yml create mode 100644 .styleci.yml create mode 100755 CHANGELOG.md create mode 100755 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 composer.json create mode 100644 phpunit.xml.dist create mode 100644 src/Exceptions/CouldNotSendNotification.php create mode 100644 src/WXWorkChannel.php create mode 100644 src/WXWorkMessage.php create mode 100644 tests/ChannelTest.php create mode 100644 tests/MessageTest.php 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/.gitattributes b/.gitattributes new file mode 100644 index 00000000..b2638710 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/.scrutinizer.yml export-ignore +/tests export-ignore diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..c77cfcc5 --- /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: [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..616e6d3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/vendor +build +composer.phar +composer.lock +.DS_Store +.phpunit.result.cache 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..7df542d8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to `wxwork` will be documented in this file + +## 0.1.0 - 2021-12-29 + +- 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..03be412e --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) Dong Lei + +> 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..9edf9d50 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,125 @@ -# New Notification Channels +# WXWork 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/wxwork.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/wxwork) +[![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/wxwork/master.svg?style=flat-square)](https://travis-ci.org/laravel-notification-channels/wxwork) +[![StyleCI](https://styleci.io/repos/443232385/shield)](https://styleci.io/repos/443232385) +[![Quality Score](https://img.shields.io/scrutinizer/g/laravel-notification-channels/wxwork.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/wxwork) +[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/laravel-notification-channels/wxwork/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/wxwork/?branch=master) +[![Total Downloads](https://img.shields.io/packagist/dt/laravel-notification-channels/wxwork.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/wxwork) -### 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 [WXWork]([link to service](https://open.work.weixin.qq.com/api/doc/90000/90136/91770)) with Laravel 5.5+, 6.x, 7.x and 8.x -## Workflow for new channels +## Contents -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. +- [WXWork Notifications Channel for Laravel](#wxwork-notifications-channel-for-laravel) + - [Contents](#contents) + - [Installation](#installation) + - [Setting up the WXWork service](#setting-up-the-wxwork-service) + - [Usage](#usage) + - [Text Notification](#text-notification) + - [Markdown Notification](#markdown-notification) + - [Available Message methods](#available-message-methods) + - [Changelog](#changelog) + - [Testing](#testing) + - [Security](#security) + - [Contributing](#contributing) + - [Credits](#credits) + - [License](#license) -Take a look at our [FAQ](http://laravel-notification-channels.com/) to see our small list of rules, to provide top-notch notification channels. + +## Installation + +You can install the package via composer: + +```bash +composer require laravel-notification-channels/wxwork +``` + +### Setting up the WXWork service + +```php +# config/services.php + +'wxwork-bot-api' => [ + 'token' => env('WXWORK_BOT_TOKEN', 'YOUR BOT TOKEN HERE'), + 'base_uri' => env('WXWORK_BOT_BASE_URI', 'YOUR BASE URI HERE') +], +``` + +## Usage + +You can now use the channel in your `via()` method inside the Notification class. + +### Text Notification + +```php +use NotificationChannels\WXWork\WXWorkMessage; +use NotificationChannels\WXWork\WXWorkChannel; +use Illuminate\Notifications\Notification; + +class InvoicePaid extends Notification +{ + public function via($notifiable) + { + return [WXWorkChannel::class]; + } + + public function toWXWork($notifiable) + { + return WXWorkMessage::create()->content("Hello there!\nYour invoice has been *PAID*")->toText(); + } +} +``` + +### Markdown Notification + +```php +use NotificationChannels\WXWork\WXWorkMessage; +use NotificationChannels\WXWork\WXWorkChannel; +use Illuminate\Notifications\Notification; + +class InvoicePaid extends Notification +{ + public function via($notifiable) + { + return [WXWorkChannel::class]; + } + + public function toWXWork($notifiable) + { + return WXWorkMessage::create()->content("Hello there!\nYour invoice has been *PAID*")->toMarkDown(); + } +} +``` + +### 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 :author_email instead of using the issue tracker. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Credits + +- [Dong Lei](https://github.com/:author_username) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..47360e01 --- /dev/null +++ b/composer.json @@ -0,0 +1,52 @@ +{ + "name": "laravel-notification-channels/wxwork", + "description": "WXWwork Noficaiton Channel for Laravel", + "keywords": [ + "wxwork notification", + "laravel", + "wxwork", + "notification", + "wxwork notifications channel" + ], + "homepage": "https://github.com/laravel-notification-channels/wxwork", + "license": "MIT", + "authors": [ + { + "name": "Dong Lei", + "email": "dlsimple@gmail.com", + "homepage": "https://www.github.com", + "role": "Developer" + } + ], + "require": { + "php": ">=7.4", + "guzzlehttp/guzzle": "^7.4", + "illuminate/contracts": "^8.77", + "illuminate/notifications": "~6.0 || ~7.0 || ~8.0", + "illuminate/support": "^8.77" + }, + "require-dev": { + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^9.0" + }, + "autoload": { + "psr-4": { + "NotificationChannels\\WXWork\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "NotificationChannels\\WXWork\\Test\\": "tests" + } + }, + "scripts": { + "test": "phpunit", + "test:coverage": "phpunit --coverage-text --coverage-clover=coverage.clover" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 00000000..23edb432 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + tests + + + + + src/ + + + + + + + + + + diff --git a/src/Exceptions/CouldNotSendNotification.php b/src/Exceptions/CouldNotSendNotification.php new file mode 100644 index 00000000..e271a5b1 --- /dev/null +++ b/src/Exceptions/CouldNotSendNotification.php @@ -0,0 +1,27 @@ +message = $message; + $this->code = $code; + + parent::__construct($message, $code); + } + + public static function wxworkRespondedWithAnError( + string $message, + ?int $code = null + ): self { + return new self( + sprintf('wxwork responded with an error: `%s`', $message), + $code + ); + } + +} diff --git a/src/WXWorkChannel.php b/src/WXWorkChannel.php new file mode 100644 index 00000000..6f8b9854 --- /dev/null +++ b/src/WXWorkChannel.php @@ -0,0 +1,85 @@ +client = $client; + $this->token = $token ?? config('services.wxwork-bot-api.token'); + $this->base_uri = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='; + + $this->url = $this->base_uri.$this->token; + } + + /** + * Send the given notification. + * + * @throws \NotificationChannels\WXWork\Exceptions\CouldNotSendNotification + */ + public function send( + mixed $notifiable, + Notification $notification + ): \GuzzleHttp\Psr7\Response { + $token = $notifiable->routeNotificationFor('wxwork'); + if (!$token) { + $token = $this->token; + } + + $message = $notification->toWXWork($notifiable); + + $response = $this->client->post($this->url, ['body' => $message]); + + $this->checkWXWorkResponseError($response); + return $response; + + + } + + protected function checkWXWorkResponseError( + \GuzzleHttp\Psr7\Response $response + ): void { + $error_msg = $response->getHeader('Error-Msg')[0]; + $error_code = intval($response->getHeader('Error-Code')[0]); + + if ($error_msg !== 'ok' || $error_code !== 0) { + throw CouldNotSendNotification::wxworkRespondedWithAnError( + $error_msg, + $error_code + ); + } + } +} diff --git a/src/WXWorkMessage.php b/src/WXWorkMessage.php new file mode 100644 index 00000000..0a26b0f5 --- /dev/null +++ b/src/WXWorkMessage.php @@ -0,0 +1,64 @@ +message = $message; + } + + /** + * Get a markdown. + */ + public static function create(string $message = ''): WXWorkMessage + { + return new self($message); + } + + public function content(string $message = ''): WXWorkMessage + { + $this->message = $message; + + return $this; + } + + public function getContent(): string + { + return $this->message; + } + + /** + * Get a markdown. + */ + public function toMarkDown(): string + { + return json_encode([ + 'msgtype' => 'markdown', + 'markdown' => [ + 'content' => $this->message, + ], + ]); + } + + /** + * Get a text. + */ + public function toText(): string + { + return json_encode([ + 'msgtype' => 'text', + 'text' => [ + 'content' => $this->message, + ], + ]); + } +} diff --git a/tests/ChannelTest.php b/tests/ChannelTest.php new file mode 100644 index 00000000..52a84e3c --- /dev/null +++ b/tests/ChannelTest.php @@ -0,0 +1,78 @@ +'ok', 'Error-Code'=>'0']); + $client = Mockery::mock(Client::class); + $message = (new WXWorkMessage('foobar'))->toMarkdown(); + $client->shouldReceive('post')->once()->with( + 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=Test_Token', + [ + 'body' => $message, + ] + )->andReturn($response); + $channel = new WXWorkChannel($client, 'Test_Token'); + $actualResponse = $channel->send(new TestNotifiable(), new TestMarkdownNotification()); + self::assertSame($response, $actualResponse); + } + + /** @test */ + public function it_can_send_a_text_notification() + { + $response = new Response(200, ['Error-Msg'=>'ok', 'Error-Code'=>'0']); + $client = Mockery::mock(Client::class); + $message = (new WXWorkMessage('foobar'))->toText(); + $client->shouldReceive('post')->once()->with( + 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=Test_Token', + [ + 'body' => $message, + ] + )->andReturn($response); + $channel = new WXWorkChannel($client, 'Test_Token'); + $actualResponse = $channel->send(new TestNotifiable(), new TestTextNotification()); + + self::assertSame($response, $actualResponse); + } +} + +class TestNotifiable +{ + use \Illuminate\Notifications\Notifiable; + + /** + * @return int + */ + public function routeNotificationForWXWork() + { + return 'Test_Token'; + } +} + +class TestTextNotification extends Notification +{ + public function toWXWork($notifiable) + { + return (new WXWorkMessage('foobar'))->ToText(); + } +} + +class TestMarkdownNotification extends Notification +{ + public function toWXWork($notifiable) + { + return (new WXWorkMessage('foobar'))->ToMarkDown(); + } +} diff --git a/tests/MessageTest.php b/tests/MessageTest.php new file mode 100644 index 00000000..a73a88b8 --- /dev/null +++ b/tests/MessageTest.php @@ -0,0 +1,41 @@ +message = new WXWorkMessage(); + } + + /** @test */ + public function it_accepts_content_when_constructing_a_message() + { + $message = new WXWorkMessage('foobar'); + + $this->assertEquals('foobar', $message->getContent()); + } + + /** @test */ + public function it_provides_a_create_method() + { + $message = WXWorkMessage::create('foobar'); + + $this->assertEquals('foobar', $message->getContent()); + } + + /** @test */ + public function it_can_set_the_wxwork_content() + { + $this->message->content('foobar'); + $this->assertEquals('foobar', $this->message->getContent()); + } +} From f2b76a0063233ccfd39c5bd635412bb7896074ee Mon Sep 17 00:00:00 2001 From: dlsimple Date: Fri, 31 Dec 2021 03:38:39 +0000 Subject: [PATCH 2/2] Apply fixes from StyleCI --- src/Exceptions/CouldNotSendNotification.php | 1 - src/WXWorkChannel.php | 8 +++----- tests/ChannelTest.php | 2 +- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/Exceptions/CouldNotSendNotification.php b/src/Exceptions/CouldNotSendNotification.php index e271a5b1..9298e081 100644 --- a/src/Exceptions/CouldNotSendNotification.php +++ b/src/Exceptions/CouldNotSendNotification.php @@ -23,5 +23,4 @@ public static function wxworkRespondedWithAnError( $code ); } - } diff --git a/src/WXWorkChannel.php b/src/WXWorkChannel.php index 6f8b9854..bd42ed86 100644 --- a/src/WXWorkChannel.php +++ b/src/WXWorkChannel.php @@ -7,7 +7,6 @@ use GuzzleHttp\Client; use Illuminate\Notifications\Notification; use NotificationChannels\WXWork\Exceptions\CouldNotSendNotification; -use Illuminate\Support\Facades\RateLimiter; final class WXWorkChannel { @@ -55,18 +54,17 @@ public function send( Notification $notification ): \GuzzleHttp\Psr7\Response { $token = $notifiable->routeNotificationFor('wxwork'); - if (!$token) { + if (! $token) { $token = $this->token; } $message = $notification->toWXWork($notifiable); $response = $this->client->post($this->url, ['body' => $message]); - - $this->checkWXWorkResponseError($response); - return $response; + $this->checkWXWorkResponseError($response); + return $response; } protected function checkWXWorkResponseError( diff --git a/tests/ChannelTest.php b/tests/ChannelTest.php index 52a84e3c..79335584 100644 --- a/tests/ChannelTest.php +++ b/tests/ChannelTest.php @@ -43,7 +43,7 @@ public function it_can_send_a_text_notification() )->andReturn($response); $channel = new WXWorkChannel($client, 'Test_Token'); $actualResponse = $channel->send(new TestNotifiable(), new TestTextNotification()); - + self::assertSame($response, $actualResponse); } }