diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..cd8eb86 --- /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 0000000..4577aeb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/.editorconfig export-ignore +/tests export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4c5d3f8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,63 @@ +name: CI + +on: [push, pull_request] + +jobs: + phplint: + runs-on: ubuntu-latest + + name: PHP Linting (Pint) + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: "laravel-pint" + uses: aglipanci/laravel-pint-action@latest + with: + preset: laravel + verboseMode: true + testMode: true + configPath: "pint.json" + pintVersion: 1.18.2 + onlyDirty: true + + test: + runs-on: ubuntu-latest + strategy: + max-parallel: 15 + fail-fast: false + matrix: + php: [8.3, 8.2] + laravel: [11.*] + stability: [prefer-lowest, prefer-stable] + include: + - laravel: 11.* + testbench: 9.* + + name: PHP${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mbstring, xdebug + coverage: xdebug + + - name: Install dependencies + run: | + composer require "illuminate/support:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --${{ matrix.stability }} --prefer-dist --no-interaction --no-suggest + + - name: Lint composer.json + run: composer validate + + - name: Run Tests + run: composer test:unit + + - name: Run Integration Tests + run: composer test:integration diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..98352d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# phpstorm project files +.idea + +# netbeans project files +nbproject + +# zend studio for eclipse project files +.buildpath +.project +.settings + +# windows thumbnail cache +Thumbs.db + +# Mac DS_Store Files +.DS_Store + +# composer +/vendor +composer.phar +composer.lock + +# phpunit +phpunit.phar +/phpunit.xml +.phpunit.result.cache + +# build +build + +# laravel/pint +.pint.cache.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 881b3ec..0b53f64 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,19 @@ # Changelog -All notable changes to `twilio` will be documented in this file +All notable changes to `laravel-notification-channels/twilio` will be documented in this file. + +## 4.0.0 + +- Added PHP Linting (Pint) to CI workflow +- Additional tests to achieve 100% code coverage by @pascalbaljet +- Update PhpUnit to 10.5 and fixed all tests. +- Bump `twilio/sdk` to 8.3 +- Improved types and use constructor property promotion everywhere. +- Added Pint and fixed PHP syntax. +- Drop support for PHP < 8.2 **BREAKING CHANGE** +- Drop support for Laravel 7.x, 8.x, 9.x, and 10.x **BREAKING CHANGE** +- Enable overriding the Twilio message source #142 +- Add enabled config option (`TWILIO_ENABLED`) to disable the channel #121 ## 3.0.0 diff --git a/README.md b/README.md index 7be4064..f2b2f48 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,11 @@ # Twilio notifications channel for Laravel -[![Latest Version on Packagist](https://img.shields.io/packagist/v/laravel-notification-channels/twilio.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/twilio) -[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) -[![Build Status](https://img.shields.io/github/workflow/status/laravel-notification-channels/twilio/PHP?style=flat-square)](https://travis-ci.org/laravel-notification-channels/twilio) -[![StyleCI](https://styleci.io/repos/65543339/shield)](https://styleci.io/repos/65543339) -[![Quality Score](https://img.shields.io/scrutinizer/g/laravel-notification-channels/twilio.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/twilio) -[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/laravel-notification-channels/twilio/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/laravel-notification-channels/twilio/?branch=master) -[![Total Downloads](https://img.shields.io/packagist/dt/laravel-notification-channels/twilio.svg?style=flat-square)](https://packagist.org/packages/laravel-notification-channels/twilio) +[![Latest Version on Packagist](https://img.shields.io/packagist/v/laravel-notification-channels/twilio.svg)](https://packagist.org/packages/laravel-notification-channels/twilio) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE.md) +[![Build Status](https://github.com/laravel-notification-channels/twilio/actions/workflows/ci.yml/badge.svg)](https://github.com/laravel-notification-channels/twilio/actions/workflows/ci.yml) +[![Total Downloads](https://img.shields.io/packagist/dt/laravel-notification-channels/twilio.svg)](https://packagist.org/packages/laravel-notification-channels/twilio) -This package makes it easy to send [Twilio notifications](https://documentation.twilio.com/docs) with Laravel 5.5+, 6.x and 7.x - -You are viewing the `3.x` documentation. [Click here](https://github.com/laravel-notification-channels/twilio/tree/2.x) to view the `2.x` documentation. +This package makes it easy to send [Twilio notifications](https://documentation.twilio.com/docs) with Laravel 11.x ## Contents @@ -26,10 +21,10 @@ You are viewing the `3.x` documentation. [Click here](https://github.com/laravel ## Installation -You can install the package via composer: +You can install the package via Composer: ``` bash -composer require laravel-notification-channels/twilio +$ composer require laravel-notification-channels/twilio ``` ### Configuration @@ -44,7 +39,8 @@ TWILIO_ACCOUNT_SID=1234 # always required TWILIO_FROM=100000000 # optional default from TWILIO_ALPHA_SENDER=HELLO # optional TWILIO_DEBUG_TO=23423423423 # Set a number that call calls/messages should be routed to for debugging -TWILIO_SMS_SERVICE_SID=MG0a0aaaaaa00aa00a00a000a00000a00a # Optional but recommended +TWILIO_SMS_SERVICE_SID=MG0a0aaaaaa00aa00a00a000a00000a00a # Optional but recommended +TWILIO_SHORTEN_URLS=true # optional, enable URL shortener ``` ### Advanced configuration @@ -57,7 +53,7 @@ Run `php artisan vendor:publish --provider="NotificationChannels\Twilio\TwilioPr #### Suppressing specific errors or all errors Publish the config using the above command, and edit the `ignored_error_codes` array. You can get the list of -exception codes from [the documentation](https://www.twilio.com/docs/api/errors). +exception codes from [the documentation](https://www.twilio.com/docs/api/errors). If you want to suppress all errors, you can set the option to `['*']`. The errors will not be logged but notification failed events will still be emitted. @@ -69,15 +65,19 @@ Twilio recommends always using a [Messaging Service](https://www.twilio.com/docs Having issues with SMS? Check Twilio's [best practices](https://www.twilio.com/docs/sms/services/services-best-practices). +## Upgrading from 3.x to 4.x + +We have dropped support for PHP < 8.2 and the minimum Laravel version is now 11. Other than that, there are no breaking changes. + ## Upgrading from 2.x to 3.x -If you're upgrading from version `2.x`, you'll need to make sure that your set environment variables match those above -in the config section. None of the environment variable names have changed, but if you used different keys in your +If you're upgrading from version `2.x`, you'll need to make sure that your set environment variables match those above +in the config section. None of the environment variable names have changed, but if you used different keys in your `services.php` config then you'll need to update them to match the above, or publish the config file and change the `env` key. - + You should also remove the old entry for `twilio` from your `services.php` config, since it's no longer used. - + The main breaking change between `2.x` and `3.x` is that failed notification will now throw an exception unless they are in the list of ignored error codes (publish the config file to edit these). @@ -131,6 +131,34 @@ class AccountApproved extends Notification } ``` +You can also send using Content Templates: + +``` php +use NotificationChannels\Twilio\TwilioChannel; +use NotificationChannels\Twilio\TwilioContentTemplateMessage; +use Illuminate\Notifications\Notification; + +class AccountApproved extends Notification +{ + public function via($notifiable) + { + return [TwilioChannel::class]; + } + + public function toTwilio($notifiable) + { + return (new TwilioContentTemplateMessage()) + ->contentSid("HXXXXXXXXXXXXXXXXXXXXXXXX") + ->contentVariables([ + '1' => 'John Doe', + '2' => 'ACME Inc.', + ]); + } +} +``` + +*Note: if sending via WhatsApp, you must add `whatsapp:` to the beginning of the phone number (i.e. `->from('whatsapp:+61428000382')`). The number must also be approved as a [WhatsApp Sender](https://www.twilio.com/console/sms/whatsapp/senders).* + Or create a Twilio call: ``` php @@ -187,7 +215,7 @@ $ composer test ## Security -If you discover any security related issues, please email gregoriohc@gmail.com instead of using the issue tracker. +If you discover any security related issues, please email pipo@onlime.ch instead of using the issue tracker. ## Contributing @@ -195,6 +223,8 @@ Please see [CONTRIBUTING](CONTRIBUTING.md) for details. ## Credits +- [Philip Iezzi (Pipo)](https://github.com/onlime) +- [Pascal Baljet](https://github.com/pascalbaljet) - [Gregorio Hernández Caso](https://github.com/gregoriohc) - [atymic](https://github.com/atymic) - [All Contributors](../../contributors) diff --git a/composer.json b/composer.json index 3047c13..3c0593c 100644 --- a/composer.json +++ b/composer.json @@ -1,13 +1,26 @@ { "name": "laravel-notification-channels/twilio", "description": "Provides Twilio notification channel for Laravel", - "keywords": ["laravel", "twilio", "notification", "sms", "call", "mms"], + "keywords": [ + "laravel", + "twilio", + "notification", + "sms", + "call", + "mms" + ], "license": "MIT", "support": { "issues": "https://github.com/laravel-notification-channels/twilio/issues", "source": "https://github.com/laravel-notification-channels/twilio" }, "authors": [ + { + "name": "Philip Iezzi", + "email": "pipo@onlime.ch", + "homepage": "https://github.com/onlime", + "role": "Developer" + }, { "name": "Gregorio Hernández Caso", "email": "gregoriohc@gmail.com", @@ -22,16 +35,18 @@ } ], "require": { - "php": ">=7.2", - "twilio/sdk": "~6.0", - "illuminate/notifications": "^5.8 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0", - "illuminate/support": "^5.8 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0", - "illuminate/events": "^5.8 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0", - "illuminate/queue": "^5.8 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0" + "php": "^8.2", + "twilio/sdk": "^7.16 || ^8.3", + "illuminate/notifications": "^11.0|^12.0|^13.0", + "illuminate/support": "^11.0|^12.0|^13.0", + "illuminate/events": "^11.0|^12.0|^13.0", + "illuminate/queue": "^11.0|^12.0|^13.0" }, "require-dev": { - "mockery/mockery": "^1.3", - "phpunit/phpunit": "^8.5" + "laravel/pint": "^1.18", + "mockery/mockery": "^1.0", + "orchestra/testbench": "^9.0", + "phpunit/phpunit": "^10.5" }, "autoload": { "psr-4": { @@ -45,8 +60,8 @@ }, "scripts": { "test": "vendor/bin/phpunit", - "test:unit": "phpunit --verbose --testsuite Unit", - "test:integration": "phpunit --verbose --testsuite Integration" + "test:unit": "phpunit --testsuite Unit", + "test:integration": "phpunit --testsuite Integration" }, "config": { "sort-packages": true diff --git a/config/twilio-notification-channel.php b/config/twilio-notification-channel.php index 04e69c6..c6a322c 100644 --- a/config/twilio-notification-channel.php +++ b/config/twilio-notification-channel.php @@ -1,6 +1,7 @@ (bool) env('TWILIO_ENABLED', true), 'username' => env('TWILIO_USERNAME'), // optional when using auth token 'password' => env('TWILIO_PASSWORD'), // optional when using auth token 'auth_token' => env('TWILIO_AUTH_TOKEN'), // optional when using username and password @@ -8,6 +9,7 @@ 'from' => env('TWILIO_FROM'), // optional 'alphanumeric_sender' => env('TWILIO_ALPHA_SENDER'), + 'shorten_urls' => (bool) env('TWILIO_SHORTEN_URLS', false), // optional, enable twilio URL shortener /** * See https://www.twilio.com/docs/sms/services. diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..939c8fb --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,26 @@ + + + + + + + + + + + + tests/Unit + + + tests/Integration + + + + + + + + src/ + + + diff --git a/pint.json b/pint.json new file mode 100644 index 0000000..bc95b72 --- /dev/null +++ b/pint.json @@ -0,0 +1,13 @@ +{ + "preset": "laravel", + "rules": { + "blank_line_before_statement": false, + "binary_operator_spaces": false, + "phpdoc_separation": false, + "modernize_strpos": true + }, + "exclude": [ + "node_modules" + ], + "cache-file": ".pint.cache.json" +} diff --git a/src/Exceptions/CouldNotSendNotification.php b/src/Exceptions/CouldNotSendNotification.php index 8428450..a94bd60 100644 --- a/src/Exceptions/CouldNotSendNotification.php +++ b/src/Exceptions/CouldNotSendNotification.php @@ -30,11 +30,4 @@ public static function invalidReceiver(): self method or a phone_number attribute to your notifiable.' ); } - - public static function missingAlphaNumericSender(): self - { - return new static( - 'Notification was not sent. Missing `alphanumeric_sender` in config' - ); - } } diff --git a/src/Twilio.php b/src/Twilio.php index 7c47881..4443a3a 100644 --- a/src/Twilio.php +++ b/src/Twilio.php @@ -10,31 +10,23 @@ class Twilio { - /** @var TwilioService */ - protected $twilioService; - - /** @var TwilioConfig */ - public $config; - - public function __construct(TwilioService $twilioService, TwilioConfig $config) - { - $this->twilioService = $twilioService; - $this->config = $config; - } + public function __construct( + protected TwilioService $twilioService, + public TwilioConfig $config + ) {} /** - * Send a TwilioMessage to the a phone number. - * - * @param TwilioMessage $message - * @param string|null $to - * @param bool $useAlphanumericSender + * Send a TwilioMessage to a phone number. * - * @return mixed * @throws TwilioException * @throws CouldNotSendNotification */ - public function sendMessage(TwilioMessage $message, ?string $to, bool $useAlphanumericSender = false) + public function sendMessage(TwilioMessage $message, ?string $to, bool $useAlphanumericSender = false): CallInstance|MessageInstance { + if ($message instanceof TwilioContentTemplateMessage) { + return $this->sendContentTemplateMessage($message, $to); + } + if ($message instanceof TwilioSmsMessage) { if ($useAlphanumericSender && $sender = $this->getAlphanumericSender()) { $message->from($sender); @@ -43,6 +35,14 @@ public function sendMessage(TwilioMessage $message, ?string $to, bool $useAlphan return $this->sendSmsMessage($message, $to); } + if ($message instanceof TwilioCallMessage) { + if ($useAlphanumericSender && $sender = $this->getAlphanumericSender()) { + $message->from($sender); + } + + return $this->sendSmsMessage($message, $to); + } + if ($message instanceof TwilioCallMessage) { return $this->makeCall($message, $to); } @@ -53,10 +53,7 @@ public function sendMessage(TwilioMessage $message, ?string $to, bool $useAlphan /** * Send an sms message using the Twilio Service. * - * @param TwilioSmsMessage $message - * @param string|null $to * - * @return MessageInstance * @throws CouldNotSendNotification * @throws TwilioException */ @@ -64,7 +61,7 @@ protected function sendSmsMessage(TwilioSmsMessage $message, ?string $to): Messa { $debugTo = $this->config->getDebugTo(); - if ($debugTo !== null) { + if (! empty($debugTo)) { $to = $debugTo; } @@ -76,6 +73,10 @@ protected function sendSmsMessage(TwilioSmsMessage $message, ?string $to): Messa $params['messagingServiceSid'] = $messagingServiceSid; } + if ($this->config->isShortenUrlsEnabled()) { + $params['ShortenUrls'] = 'true'; + } + if ($from = $this->getFrom($message)) { $params['from'] = $from; } @@ -100,21 +101,74 @@ protected function sendSmsMessage(TwilioSmsMessage $message, ?string $to): Messa ]); } + if ($message instanceof TwilioContentTemplateMessage) { + $this->fillOptionalParams($params, $message, [ + 'contentSid', + 'contentVariables', + ]); + } + + return $this->twilioService->messages->create($to, $params); + } + + protected function sendContentTemplateMessage(TwilioContentTemplateMessage $message, ?string $to): MessageInstance + { + $debugTo = $this->config->getDebugTo(); + + if (! empty($debugTo)) { + $to = $debugTo; + } + + $params = [ + 'to' => $to, + ]; + + if ($messagingServiceSid = $this->getMessagingServiceSid($message)) { + $params['messagingServiceSid'] = $messagingServiceSid; + } + + if ($this->config->isShortenUrlsEnabled()) { + $params['ShortenUrls'] = 'true'; + } + + if ($from = $this->getFrom($message)) { + $params['from'] = $from; + } + + $this->fillOptionalParams($params, $message, [ + 'statusCallback', + 'statusCallbackMethod', + 'applicationSid', + 'forceDelivery', + 'maxPrice', + 'provideFeedback', + 'validityPeriod', + 'contentSid', + 'contentVariables', + ]); + + if (empty($from) && empty($messagingServiceSid)) { + throw CouldNotSendNotification::missingFrom(); + } + return $this->twilioService->messages->create($to, $params); } /** * Make a call using the Twilio Service. * - * @param TwilioCallMessage $message - * @param string|null $to * - * @return CallInstance * @throws TwilioException * @throws CouldNotSendNotification */ protected function makeCall(TwilioCallMessage $message, ?string $to): CallInstance { + $debugTo = $this->config->getDebugTo(); + + if ($debugTo !== null) { + $to = $debugTo; + } + $params = [ 'url' => trim($message->content), ]; @@ -141,9 +195,6 @@ protected function makeCall(TwilioCallMessage $message, ?string $to): CallInstan /** * Get the from address from message, or config. - * - * @param TwilioMessage $message - * @return string|null */ protected function getFrom(TwilioMessage $message): ?string { @@ -152,9 +203,6 @@ protected function getFrom(TwilioMessage $message): ?string /** * Get the messaging service SID from message, or config. - * - * @param TwilioSmsMessage $message - * @return string|null */ protected function getMessagingServiceSid(TwilioSmsMessage $message): ?string { @@ -163,21 +211,13 @@ protected function getMessagingServiceSid(TwilioSmsMessage $message): ?string /** * Get the alphanumeric sender from config, if one exists. - * - * @return string|null */ protected function getAlphanumericSender(): ?string { return $this->config->getAlphanumericSender(); } - /** - * @param array $params - * @param TwilioMessage $message - * @param array $optionalParams - * @return Twilio - */ - protected function fillOptionalParams(&$params, $message, $optionalParams): self + protected function fillOptionalParams(array &$params, TwilioMessage $message, array $optionalParams): self { foreach ($optionalParams as $optionalParam) { if ($message->$optionalParam) { diff --git a/src/TwilioCallMessage.php b/src/TwilioCallMessage.php index da4b160..2d81eeb 100755 --- a/src/TwilioCallMessage.php +++ b/src/TwilioCallMessage.php @@ -5,33 +5,19 @@ class TwilioCallMessage extends TwilioMessage { public const STATUS_CANCELED = 'canceled'; + public const STATUS_COMPLETED = 'completed'; - /** - * @var null|string - */ - public $method; + public ?string $method = null; - /** - * @var null|string - */ - public $status; + public ?string $status = null; - /** - * @var null|string - */ - public $fallbackUrl; + public ?string $fallbackUrl = null; - /** - * @var null|string - */ - public $fallbackMethod; + public ?string $fallbackMethod = null; /** * Set the message url. - * - * @param string $url - * @return $this */ public function url(string $url): self { @@ -42,11 +28,8 @@ public function url(string $url): self /** * Set the message url request method. - * - * @param string $method - * @return $this */ - public function method($method): self + public function method(string $method): self { $this->method = $method; @@ -55,9 +38,6 @@ public function method($method): self /** * Set the status for the current calls. - * - * @param string $status - * @return $this */ public function status(string $status): self { @@ -68,9 +48,6 @@ public function status(string $status): self /** * Set the fallback url. - * - * @param string $fallbackUrl - * @return $this */ public function fallbackUrl(string $fallbackUrl): self { @@ -81,9 +58,6 @@ public function fallbackUrl(string $fallbackUrl): self /** * Set the fallback url request method. - * - * @param string $fallbackMethod - * @return $this */ public function fallbackMethod(string $fallbackMethod): self { diff --git a/src/TwilioChannel.php b/src/TwilioChannel.php index 0ce8aea..f7c9dbc 100755 --- a/src/TwilioChannel.php +++ b/src/TwilioChannel.php @@ -10,42 +10,26 @@ class TwilioChannel { - /** - * @var Twilio - */ - protected $twilio; - - /** - * @var Dispatcher - */ - protected $events; - - /** - * TwilioChannel constructor. - * - * @param Twilio $twilio - * @param Dispatcher $events - */ - public function __construct(Twilio $twilio, Dispatcher $events) - { - $this->twilio = $twilio; - $this->events = $events; - } + public function __construct( + protected Twilio $twilio, + protected Dispatcher $events + ) {} /** * Send the given notification. * - * @param mixed $notifiable - * @param Notification $notification - * * @return mixed * @throws Exception */ - public function send($notifiable, Notification $notification) + public function send(mixed $notifiable, Notification $notification) { + if (! $this->isEnabled()) { + return; + } + try { - $to = $this->getTo($notifiable); - $message = $notification->toTwilio($notifiable); + $to = $this->getTo($notifiable, $notification); + $message = $this->getMessage($notifiable, $notification); $useSender = $this->canReceiveAlphanumericSender($notifiable); if (is_string($message)) { @@ -75,21 +59,40 @@ public function send($notifiable, Notification $notification) } } + /** + * Get the message to send. + * + * @return mixed + */ + protected function getMessage(mixed $notifiable, Notification $notification) + { + return $notification->toTwilio($notifiable); + } + + /** + * Check if twilio is enabled. + */ + protected function isEnabled(): bool + { + return $this->twilio->config->enabled() ?? true; + } + /** * Get the address to send a notification to. * - * @param mixed $notifiable + * @param mixed $notifiable + * @param Notification|null $notification * * @return mixed * @throws CouldNotSendNotification */ - protected function getTo($notifiable) + protected function getTo($notifiable, $notification = null) { - if ($notifiable->routeNotificationFor(self::class)) { - return $notifiable->routeNotificationFor(self::class); + if ($notifiable->routeNotificationFor(self::class, $notification)) { + return $notifiable->routeNotificationFor(self::class, $notification); } - if ($notifiable->routeNotificationFor('twilio')) { - return $notifiable->routeNotificationFor('twilio'); + if ($notifiable->routeNotificationFor('twilio', $notification)) { + return $notifiable->routeNotificationFor('twilio', $notification); } if (isset($notifiable->phone_number)) { return $notifiable->phone_number; @@ -101,7 +104,6 @@ protected function getTo($notifiable) /** * Get the alphanumeric sender. * - * @param $notifiable * * @return mixed|null * @throws CouldNotSendNotification diff --git a/src/TwilioConfig.php b/src/TwilioConfig.php index 5334258..653dc08 100644 --- a/src/TwilioConfig.php +++ b/src/TwilioConfig.php @@ -4,15 +4,13 @@ class TwilioConfig { - /** @var array */ - private $config; + public function __construct( + private readonly array $config + ) {} - /** - * @param array $config - */ - public function __construct(array $config) + public function enabled(): bool { - $this->config = $config; + return $this->config['enabled'] ?? true; } public function usingUsernamePasswordAuth(): bool @@ -78,4 +76,9 @@ public function isIgnoredErrorCode(int $code): bool return in_array($code, $this->getIgnoredErrorCodes(), true); } + + public function isShortenUrlsEnabled(): bool + { + return $this->config['shorten_urls'] ?? false; + } } diff --git a/src/TwilioContentTemplateMessage.php b/src/TwilioContentTemplateMessage.php new file mode 100644 index 0000000..e1e9c73 --- /dev/null +++ b/src/TwilioContentTemplateMessage.php @@ -0,0 +1,43 @@ +contentSid = $contentSid; + + return $this; + } + + /** + * Set the content variables. + * + * @param array $contentVariables The variables to replace in the content template (i.e. ['1' => 'John Doe']) + * @return $this + */ + public function contentVariables(array $contentVariables): self + { + $this->contentVariables = json_encode($contentVariables, JSON_FORCE_OBJECT); + return $this; + } +} diff --git a/src/TwilioMessage.php b/src/TwilioMessage.php index 8e44f8a..5e317b1 100755 --- a/src/TwilioMessage.php +++ b/src/TwilioMessage.php @@ -4,55 +4,32 @@ abstract class TwilioMessage { - /** - * The message content. - * - * @var string - */ - public $content; - /** * The phone number the message should be sent from. - * - * @var string */ - public $from; + public ?string $from = null; - /** - * @var null|string - */ - public $statusCallback; + public ?string $statusCallback = null; + + public ?string $statusCallbackMethod = null; /** - * @var null|string + * Create a new message instance. */ - public $statusCallbackMethod; + public function __construct( + public string $content = '' + ) {} /** * Create a message object. - * @param string $content - * @return static */ public static function create(string $content = ''): self { return new static($content); } - /** - * Create a new message instance. - * - * @param string $content - */ - public function __construct(string $content = '') - { - $this->content = $content; - } - /** * Set the message content. - * - * @param string $content - * @return $this */ public function content(string $content): self { @@ -63,9 +40,6 @@ public function content(string $content): self /** * Set the phone number the message should be sent from. - * - * @param string $from - * @return $this */ public function from(string $from): self { @@ -76,8 +50,6 @@ public function from(string $from): self /** * Get the from address. - * - * @return string|null */ public function getFrom(): ?string { @@ -86,9 +58,6 @@ public function getFrom(): ?string /** * Set the status callback. - * - * @param string $statusCallback - * @return $this */ public function statusCallback(string $statusCallback): self { @@ -99,9 +68,6 @@ public function statusCallback(string $statusCallback): self /** * Set the status callback request method. - * - * @param string $statusCallbackMethod - * @return $this */ public function statusCallbackMethod(string $statusCallbackMethod): self { diff --git a/src/TwilioMmsMessage.php b/src/TwilioMmsMessage.php index 1bb2dd5..3e10bde 100755 --- a/src/TwilioMmsMessage.php +++ b/src/TwilioMmsMessage.php @@ -4,16 +4,10 @@ class TwilioMmsMessage extends TwilioSmsMessage { - /** - * @var string|null - */ - public $mediaUrl; + public ?string $mediaUrl = null; /** * Set the message media url. - * - * @param string $url - * @return $this */ public function mediaUrl(string $url): self { diff --git a/src/TwilioProvider.php b/src/TwilioProvider.php index 19020ef..8f3b4b8 100755 --- a/src/TwilioProvider.php +++ b/src/TwilioProvider.php @@ -14,14 +14,12 @@ class TwilioProvider extends ServiceProvider implements DeferrableProvider /** * Bootstrap the application services. */ - public function boot() - { - } + public function boot() {} /** * Register the application services. */ - public function register() + public function register(): void { $this->mergeConfigFrom(__DIR__.'/../config/twilio-notification-channel.php', 'twilio-notification-channel'); @@ -65,15 +63,13 @@ public function register() /** * Get the services provided by the provider. - * - * @return array */ public function provides(): array { return [ + TwilioChannel::class, TwilioConfig::class, TwilioService::class, - TwilioChannel::class, ]; } } diff --git a/src/TwilioSmsMessage.php b/src/TwilioSmsMessage.php index f97c258..5479bb1 100755 --- a/src/TwilioSmsMessage.php +++ b/src/TwilioSmsMessage.php @@ -4,45 +4,22 @@ class TwilioSmsMessage extends TwilioMessage { - /** - * @var null|string - */ - public $alphaNumSender; + public ?string $alphaNumSender = null; - /** - * @var null|string - */ - public $messagingServiceSid; + public ?string $messagingServiceSid = null; - /** - * @var null|string - */ - public $applicationSid; + public ?string $applicationSid = null; - /** - * @var null|bool - */ - public $forceDelivery; + public ?bool $forceDelivery = null; - /** - * @var null|float - */ - public $maxPrice; + public ?float $maxPrice = null; - /** - * @var null|bool - */ - public $provideFeedback; + public ?bool $provideFeedback = null; - /** - * @var null|int - */ - public $validityPeriod; + public ?int $validityPeriod = null; /** * Get the from address of this message. - * - * @return null|string */ public function getFrom(): ?string { @@ -59,9 +36,6 @@ public function getFrom(): ?string /** * Set the messaging service SID. - * - * @param string $messagingServiceSid - * @return $this */ public function messagingServiceSid(string $messagingServiceSid): self { @@ -72,8 +46,6 @@ public function messagingServiceSid(string $messagingServiceSid): self /** * Get the messaging service SID of this message. - * - * @return null|string */ public function getMessagingServiceSid(): ?string { @@ -82,9 +54,6 @@ public function getMessagingServiceSid(): ?string /** * Set the alphanumeric sender. - * - * @param string $sender - * @return $this */ public function sender(string $sender): self { @@ -95,9 +64,6 @@ public function sender(string $sender): self /** * Set application SID for the message status callback. - * - * @param string $applicationSid - * @return $this */ public function applicationSid(string $applicationSid): self { @@ -108,9 +74,6 @@ public function applicationSid(string $applicationSid): self /** * Set force delivery (Deliver message without validation). - * - * @param bool $forceDelivery - * @return $this */ public function forceDelivery(bool $forceDelivery): self { @@ -121,9 +84,6 @@ public function forceDelivery(bool $forceDelivery): self /** * Set the max price (in USD dollars). - * - * @param float $maxPrice - * @return $this */ public function maxPrice(float $maxPrice): self { @@ -134,9 +94,6 @@ public function maxPrice(float $maxPrice): self /** * Set the provide feedback option. - * - * @param bool $provideFeedback - * @return $this */ public function provideFeedback(bool $provideFeedback): self { @@ -147,10 +104,6 @@ public function provideFeedback(bool $provideFeedback): self /** * Set the validity period (in seconds). - * - * @param int $validityPeriodSeconds - * - * @return $this */ public function validityPeriod(int $validityPeriodSeconds): self { diff --git a/tests/Integration/TwilioProviderTest.php b/tests/Integration/TwilioProviderTest.php new file mode 100644 index 0000000..5c526b9 --- /dev/null +++ b/tests/Integration/TwilioProviderTest.php @@ -0,0 +1,62 @@ +expectException(InvalidConfigException::class); + + $this->app->get(TwilioChannel::class); + } + + /** @test */ + public function it_cannot_create_the_application_without_sid() + { + $this->app['config']->set('twilio-notification-channel.username', 'test'); + $this->app['config']->set('twilio-notification-channel.username', 'password'); + + $this->expectException(InvalidConfigException::class); + $this->app->get(TwilioChannel::class); + } + + /** @test */ + public function it_can_create_the_application_with_sid() + { + $this->app['config']->set('twilio-notification-channel.username', 'test'); + $this->app['config']->set('twilio-notification-channel.password', 'password'); + $this->app['config']->set('twilio-notification-channel.account_sid', '1234'); + + $this->assertInstanceOf(TwilioChannel::class, $this->app->get(TwilioChannel::class)); + } + + /** @test */ + public function it_can_create_the_application_with_token_auth() + { + $this->app['config']->set('twilio-notification-channel.auth_token', 'token'); + $this->app['config']->set('twilio-notification-channel.account_sid', '1234'); + + $this->assertInstanceOf(TwilioChannel::class, $this->app->get(TwilioChannel::class)); + } + + /** @test */ + public function it_provides_three_classes() + { + $provides = (new TwilioProvider($this->app))->provides(); + + $this->assertTrue(in_array(TwilioChannel::class, $provides)); + $this->assertTrue(in_array(TwilioConfig::class, $provides)); + $this->assertTrue(in_array(Client::class, $provides)); + } +} diff --git a/tests/IntegrationTestCase.php b/tests/IntegrationTestCase.php new file mode 100644 index 0000000..087ad9a --- /dev/null +++ b/tests/IntegrationTestCase.php @@ -0,0 +1,16 @@ +twilioService = Mockery::mock(TwilioService::class); + $this->twilioService->messages = Mockery::mock(MessageList::class); + $this->twilioService->calls = Mockery::mock(CallList::class); + + $this->events = Mockery::mock(Dispatcher::class); + $this->notification = Mockery::mock(Notification::class); + } + + /** @test */ + public function it_can_send_a_sms_message() + { + $message = TwilioSmsMessage::create('Message text'); + $this->notification->shouldReceive('toTwilio')->andReturn($message); + + $config = new TwilioConfig([ + 'from' => '+31612345678', + ]); + $twilio = new Twilio($this->twilioService, $config); + $channel = new TwilioChannel($twilio, $this->events); + + $this->smsMessageWillBeSentToTwilioWith('+22222222222', [ + 'from' => '+31612345678', + 'body' => 'Message text', + ]); + + $channel->send(new NotifiableWithAttribute, $this->notification); + } + + /** @test */ + public function it_can_send_a_sms_message_using_service() + { + $message = TwilioSmsMessage::create('Message text'); + $this->notification->shouldReceive('toTwilio')->andReturn($message); + + $config = new TwilioConfig([ + 'from' => '+31612345678', + 'sms_service_sid' => '0123456789', + ]); + $twilio = new Twilio($this->twilioService, $config); + $channel = new TwilioChannel($twilio, $this->events); + + $this->smsMessageWillBeSentToTwilioWith('+22222222222', [ + 'from' => '+31612345678', + 'body' => 'Message text', + 'messagingServiceSid' => '0123456789', + ]); + + $channel->send(new NotifiableWithAttribute, $this->notification); + } + + /** @test */ + public function it_can_send_a_sms_message_using_url_shortener() + { + $message = TwilioSmsMessage::create('Message text'); + $this->notification->shouldReceive('toTwilio')->andReturn($message); + + $config = new TwilioConfig([ + 'from' => '+31612345678', + 'shorten_urls' => true, + ]); + $twilio = new Twilio($this->twilioService, $config); + $channel = new TwilioChannel($twilio, $this->events); + + $this->smsMessageWillBeSentToTwilioWith('+22222222222', [ + 'from' => '+31612345678', + 'body' => 'Message text', + 'ShortenUrls' => 'true', + ]); + + $channel->send(new NotifiableWithAttribute, $this->notification); + } + + /** @test */ + public function it_can_send_a_sms_message_using_alphanumeric_sender() + { + $message = TwilioSmsMessage::create('Message text'); + $this->notification->shouldReceive('toTwilio')->andReturn($message); + + $config = new TwilioConfig([ + 'from' => '+31612345678', + 'alphanumeric_sender' => 'TwilioTest', + ]); + $twilio = new Twilio($this->twilioService, $config); + $channel = new TwilioChannel($twilio, $this->events); + + $this->smsMessageWillBeSentToTwilioWith('+33333333333', [ + 'from' => 'TwilioTest', + 'body' => 'Message text', + ]); + + $channel->send(new NotifiableWithAlphanumericSender, $this->notification); + } + + /** @test */ + public function it_can_make_a_call() + { + $message = TwilioCallMessage::create('http://example.com'); + $this->notification->shouldReceive('toTwilio')->andReturn($message); + + $config = new TwilioConfig([ + 'from' => '+31612345678', + ]); + $twilio = new Twilio($this->twilioService, $config); + $channel = new TwilioChannel($twilio, $this->events); + + $this->callWillBeSentToTwilioWith('+22222222222', '+31612345678', [ + 'url' => 'http://example.com', + ]); + + $channel->send(new NotifiableWithAttribute, $this->notification); + } + + /** @test */ + public function it_cant_make_a_call_when_the_from_config_is_missing() + { + $message = TwilioCallMessage::create('http://example.com'); + $this->notification->shouldReceive('toTwilio')->andReturn($message); + + $config = new TwilioConfig([]); + $twilio = new Twilio($this->twilioService, $config); + $channel = new TwilioChannel($twilio, $this->events); + + $this->twilioService->calls->shouldNotReceive('create'); + + $this->events->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->expectException(CouldNotSendNotification::class); + + $channel->send(new NotifiableWithAttribute, $this->notification); + } + + protected function smsMessageWillBeSentToTwilioWith(...$args) + { + $this->twilioService->messages->shouldReceive('create') + ->atLeast()->once() + ->with(...$args) + ->andReturn(Mockery::mock(MessageInstance::class)); + } + + protected function callWillBeSentToTwilioWith(...$args) + { + $this->twilioService->calls->shouldReceive('create') + ->atLeast()->once() + ->with(...$args) + ->andReturn(Mockery::mock(CallInstance::class)); + } +} diff --git a/tests/Unit/TwilioCallMessageTest.php b/tests/Unit/TwilioCallMessageTest.php new file mode 100644 index 0000000..19de9ad --- /dev/null +++ b/tests/Unit/TwilioCallMessageTest.php @@ -0,0 +1,61 @@ +message = new TwilioCallMessage; + } + + /** @test */ + public function it_can_accept_a_message_when_constructing_a_message() + { + $message = new TwilioCallMessage('http://example.com'); + + $this->assertEquals('http://example.com', $message->content); + } + + /** @test */ + public function it_provides_a_create_method() + { + $message = TwilioCallMessage::create('http://example.com'); + + $this->assertEquals('http://example.com', $message->content); + } + + /** @test */ + public function it_can_set_the_url() + { + $this->message->url('http://example.com'); + + $this->assertEquals('http://example.com', $this->message->content); + } + + /** @test */ + public function it_can_set_optional_parameters() + { + $message = TwilioCallMessage::create('myMessage'); + $message->status(TwilioCallMessage::STATUS_CANCELED); + $message->method('PUT'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->fallbackUrl('http://example.com'); + $message->fallbackMethod('PUT'); + + $this->assertEquals(TwilioCallMessage::STATUS_CANCELED, $message->status); + $this->assertEquals('PUT', $message->method); + $this->assertEquals('http://example.com', $message->statusCallback); + $this->assertEquals('PUT', $message->statusCallbackMethod); + $this->assertEquals('http://example.com', $message->fallbackUrl); + $this->assertEquals('PUT', $message->fallbackMethod); + } +} diff --git a/tests/Unit/TwilioChannelTest.php b/tests/Unit/TwilioChannelTest.php new file mode 100644 index 0000000..cf04cd0 --- /dev/null +++ b/tests/Unit/TwilioChannelTest.php @@ -0,0 +1,294 @@ +twilio = Mockery::mock(Twilio::class); + $this->twilio->config = new TwilioConfig([]); + $this->dispatcher = Mockery::mock(Dispatcher::class); + + $this->channel = new TwilioChannel($this->twilio, $this->dispatcher); + } + + /** @test */ + public function it_will_not_send_a_message_if_not_enabled() + { + $notifiable = new Notifiable; + $notification = Mockery::mock(Notification::class); + + $this->twilio->config = new TwilioConfig([ + 'enabled' => false, + ]); + + $this->dispatcher->shouldNotReceive('dispatch'); + + $result = $this->channel->send($notifiable, $notification); + + $this->assertNull($result); + } + + /** @test */ + public function it_will_not_send_a_message_without_known_receiver() + { + $notifiable = new Notifiable; + $notification = Mockery::mock(Notification::class); + + $this->twilio->config = new TwilioConfig([ + 'ignored_error_codes' => [], + ]); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->expectException(CouldNotSendNotification::class); + + $result = $this->channel->send($notifiable, $notification); + + $this->assertNull($result); + } + + /** @test */ + public function it_will_send_a_sms_message_to_the_result_of_the_route_method_of_the_notifiable() + { + $notifiable = new NotifiableWithMethod; + $notification = Mockery::mock(Notification::class); + + $message = new TwilioSmsMessage('Message text'); + $notification->shouldReceive('toTwilio')->andReturn($message); + + $this->twilio->shouldReceive('sendMessage') + ->atLeast()->once() + ->with($message, '+1111111111', false); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_send_a_sms_message_to_the_result_of_the_route_method_of_the_notifiable_if_it_uses_the_twilio_channel_explicitly() + { + $notifiable = new NotifiableWithTwilioChannel; + $notification = Mockery::mock(Notification::class); + + $message = new TwilioSmsMessage('Message text'); + $notification->shouldReceive('toTwilio')->andReturn($message); + + $this->twilio->shouldReceive('sendMessage') + ->atLeast()->once() + ->with($message, '+1111111111', false); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_make_a_call_to_the_phone_number_attribute_of_the_notifiable() + { + $notifiable = new NotifiableWithAttribute; + $notification = Mockery::mock(Notification::class); + + $message = new TwilioCallMessage('http://example.com'); + $notification->shouldReceive('toTwilio')->andReturn($message); + + $this->twilio->shouldReceive('sendMessage') + ->atLeast()->once() + ->with($message, '+22222222222', false); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_convert_a_string_to_a_sms_message() + { + $notifiable = new NotifiableWithAttribute; + $notification = Mockery::mock(Notification::class); + + $notification->shouldReceive('toTwilio')->andReturn('Message text'); + + $this->twilio->shouldReceive('sendMessage') + ->atLeast()->once() + ->with(Mockery::type(TwilioSmsMessage::class), Mockery::any(), false); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_fire_an_event_in_case_of_an_invalid_message() + { + $notifiable = new NotifiableWithAttribute; + $notification = Mockery::mock(Notification::class); + + $this->twilio->config = new TwilioConfig([ + 'ignored_error_codes' => [], + ]); + + // Invalid message + $notification->shouldReceive('toTwilio')->andReturn(-1); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->expectException(CouldNotSendNotification::class); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_ignore_specific_error_codes() + { + $notifiable = new NotifiableWithAttribute; + $notification = Mockery::mock(Notification::class); + + $this->twilio->config = new TwilioConfig([ + 'ignored_error_codes' => [ + 44444, + ], + ]); + + $notification->shouldReceive('toTwilio')->andReturn('Message text'); + + $this->twilio->shouldReceive('sendMessage') + ->andThrow(new RestException('error', 44444, 400)); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_rethrow_non_ignored_error_codes() + { + $notifiable = new NotifiableWithAttribute; + $notification = Mockery::mock(Notification::class); + + $this->twilio->config = new TwilioConfig([ + 'ignored_error_codes' => [ + 55555, + ], + ]); + + $notification->shouldReceive('toTwilio')->andReturn('Message text'); + + $this->twilio->shouldReceive('sendMessage') + ->andThrow(new RestException('error', 44444, 400)); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->expectException(RestException::class); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_ignore_all_error_codes() + { + $notifiable = new NotifiableWithAttribute; + $notification = Mockery::mock(Notification::class); + + $this->twilio->config = new TwilioConfig([ + 'ignored_error_codes' => ['*'], + ]); + + $notification->shouldReceive('toTwilio')->andReturn('Message text'); + + $this->twilio->shouldReceive('sendMessage') + ->andThrow(new RestException('error', 44444, 400)); + + $this->dispatcher->shouldReceive('dispatch') + ->atLeast()->once() + ->with(Mockery::type(NotificationFailed::class)); + + $this->channel->send($notifiable, $notification); + } + + /** @test */ + public function it_will_send_using_alphanumeric_if_notifiable_can_receive() + { + $notifiable = new NotifiableWithAlphanumericSender; + $notification = Mockery::mock(Notification::class); + + $message = new TwilioSmsMessage('Message text'); + $notification->shouldReceive('toTwilio')->andReturn($message); + + $this->twilio->shouldReceive('sendMessage') + ->atLeast()->once() + ->with($message, '+33333333333', true); + + $this->channel->send($notifiable, $notification); + } +} + +class Notifiable +{ + public $phone_number = null; + + public function routeNotificationFor() {} +} + +class NotifiableWithTwilioChannel +{ + public function routeNotificationFor(string $channel) + { + if ($channel === 'twilio') { + return '+1111111111'; + } + } +} + +class NotifiableWithMethod +{ + public function routeNotificationFor() + { + return '+1111111111'; + } +} + +class NotifiableWithAttribute +{ + public $phone_number = '+22222222222'; + + public function routeNotificationFor() {} +} + +class NotifiableWithAlphanumericSender +{ + public $phone_number = '+33333333333'; + + public function routeNotificationFor() {} + + public function canReceiveAlphanumericSender() + { + return true; + } +} diff --git a/tests/Unit/TwilioConfigTest.php b/tests/Unit/TwilioConfigTest.php new file mode 100644 index 0000000..8ab041e --- /dev/null +++ b/tests/Unit/TwilioConfigTest.php @@ -0,0 +1,124 @@ +assertTrue($this->config()->enabled()); // defaults to true + $this->assertTrue($this->config(['enabled' => true])->enabled()); + $this->assertFalse($this->config(['enabled' => false])->enabled()); + } + + /** @test */ + public function it_defaults_to_null_for_config_keys_with_a_string_return_type() + { + $config = $this->config(); + + $this->assertNull($config->getAuthToken()); + $this->assertNull($config->getUsername()); + $this->assertNull($config->getPassword()); + $this->assertNull($config->getAccountSid()); + $this->assertNull($config->getFrom()); + $this->assertNull($config->getAlphanumericSender()); + $this->assertNull($config->getServiceSid()); + $this->assertNull($config->getDebugTo()); + } + + /** @test */ + public function it_returns_a_string_for_config_keys_with_a_string_return_type() + { + $config = $this->config([ + 'auth_token' => 'valid-auth-token', + 'username' => 'valid-username', + 'password' => 'valid-password', + 'account_sid' => 'valid-account-sid', + 'from' => 'valid-from', + 'alphanumeric_sender' => 'valid-alphanumeric-sender', + 'sms_service_sid' => 'valid-sms-service-sid', + 'debug_to' => 'valid-debug-to', + ]); + + $this->assertEquals('valid-auth-token', $config->getAuthToken()); + $this->assertEquals('valid-username', $config->getUsername()); + $this->assertEquals('valid-password', $config->getPassword()); + $this->assertEquals('valid-account-sid', $config->getAccountSid()); + $this->assertEquals('valid-from', $config->getFrom()); + $this->assertEquals('valid-alphanumeric-sender', $config->getAlphanumericSender()); + $this->assertEquals('valid-sms-service-sid', $config->getServiceSid()); + $this->assertEquals('valid-debug-to', $config->getDebugTo()); + } + + /** @test */ + public function it_returns_an_array_of_ignored_codes() + { + $this->assertEquals([], $this->config()->getIgnoredErrorCodes()); // defaults to empty array + $this->assertEquals([1, 2], $this->config(['ignored_error_codes' => [1, 2]])->getIgnoredErrorCodes()); + } + + /** @test */ + public function it_returns_a_boolean_wether_the_error_code_is_ignored_or_not() + { + $config = $this->config(['ignored_error_codes' => [1, 2]]); + $this->assertTrue($config->isIgnoredErrorCode(1)); + $this->assertTrue($config->isIgnoredErrorCode(2)); + $this->assertFalse($config->isIgnoredErrorCode(3)); + + $config = $this->config(['ignored_error_codes' => ['*']]); + $this->assertTrue($config->isIgnoredErrorCode(1)); + $this->assertTrue($config->isIgnoredErrorCode(2)); + $this->assertTrue($config->isIgnoredErrorCode(3)); + } + + /** @test */ + public function it_returns_a_boolean_wether_shorten_urls_is_enabled_or_not() + { + $this->assertFalse($this->config()->isShortenUrlsEnabled()); // defaults to false + $this->assertTrue($this->config(['shorten_urls' => true])->isShortenUrlsEnabled()); + $this->assertFalse($this->config(['shorten_urls' => false])->isShortenUrlsEnabled()); + } + + /** @test */ + public function it_returns_a_boolean_wether_token_auth_is_used_or_not() + { + // No values set... + $this->assertFalse($this->config()->usingTokenAuth()); + + // One value set... + $this->assertFalse($this->config(['auth_token' => 'valid'])->usingTokenAuth()); + $this->assertFalse($this->config(['account_sid' => 'valid'])->usingTokenAuth()); + + // Both values set... + $this->assertTrue($this->config(['auth_token' => 'valid', 'account_sid' => 'valid'])->usingTokenAuth()); + } + + /** @test */ + public function it_returns_a_boolean_wether_username_password_auth_is_used_or_not() + { + // No values set... + $this->assertFalse($this->config()->usingUsernamePasswordAuth()); + + // One value set... + $this->assertFalse($this->config(['username' => 'valid'])->usingUsernamePasswordAuth()); + $this->assertFalse($this->config(['password' => 'valid'])->usingUsernamePasswordAuth()); + $this->assertFalse($this->config(['account_sid' => 'valid'])->usingUsernamePasswordAuth()); + + // Two values set... + $this->assertFalse($this->config(['username' => 'valid', 'password' => 'valid'])->usingUsernamePasswordAuth()); + $this->assertFalse($this->config(['username' => 'valid', 'account_sid' => 'valid'])->usingUsernamePasswordAuth()); + $this->assertFalse($this->config(['password' => 'valid', 'account_sid' => 'valid'])->usingUsernamePasswordAuth()); + + // All values set... + $this->assertTrue($this->config(['username' => 'valid', 'password' => 'valid', 'account_sid' => 'valid'])->usingUsernamePasswordAuth()); + } +} diff --git a/tests/Unit/TwilioMessageTestCase.php b/tests/Unit/TwilioMessageTestCase.php new file mode 100644 index 0000000..628e852 --- /dev/null +++ b/tests/Unit/TwilioMessageTestCase.php @@ -0,0 +1,42 @@ +message->content('myMessage'); + + $this->assertEquals('myMessage', $this->message->content); + } + + /** @test */ + public function it_can_set_the_from() + { + $this->message->from('+1234567890'); + + $this->assertEquals('+1234567890', $this->message->from); + } + + /** @test */ + public function it_can_return_the_from_using_getter() + { + $this->message->from('+1234567890'); + + $this->assertEquals('+1234567890', $this->message->getFrom()); + } +} diff --git a/tests/Unit/TwilioMmsMessageTest.php b/tests/Unit/TwilioMmsMessageTest.php new file mode 100644 index 0000000..148b1d5 --- /dev/null +++ b/tests/Unit/TwilioMmsMessageTest.php @@ -0,0 +1,81 @@ +message = new TwilioMmsMessage; + } + + /** @test */ + public function it_can_accept_a_message_when_constructing_a_message() + { + $message = new TwilioMmsMessage('myMessage'); + + $this->assertEquals('myMessage', $message->content); + } + + /** @test */ + public function it_provides_a_create_method() + { + $message = TwilioMmsMessage::create('myMessage'); + + $this->assertEquals('myMessage', $message->content); + } + + /** @test */ + public function it_sets_alphanumeric_sender() + { + $message = TwilioMmsMessage::create('myMessage'); + $message->sender('TestSender'); + + $this->assertEquals('TestSender', $message->alphaNumSender); + } + + /** @test */ + public function it_sets_media_url() + { + $message = TwilioMmsMessage::create('myMessage'); + $message->mediaUrl('https://picsum.photos/300'); + + $this->assertEquals('https://picsum.photos/300', $message->mediaUrl); + } + + /** @test */ + public function it_can_return_the_alphanumeric_sender_if_set() + { + $message = TwilioMmsMessage::create('myMessage'); + $message->sender('TestSender'); + + $this->assertEquals('TestSender', $message->getFrom()); + } + + /** @test */ + public function it_can_set_optional_parameters() + { + $message = TwilioMmsMessage::create('myMessage'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->applicationSid('ABCD1234'); + $message->forceDelivery(true); + $message->maxPrice(0.05); + $message->provideFeedback(true); + $message->validityPeriod(120); + $message->mediaUrl('http://example.com'); + + $this->assertEquals('http://example.com', $message->statusCallback); + $this->assertEquals('PUT', $message->statusCallbackMethod); + $this->assertEquals('ABCD1234', $message->applicationSid); + $this->assertEquals(true, $message->forceDelivery); + $this->assertEquals(0.05, $message->maxPrice); + $this->assertEquals(true, $message->provideFeedback); + $this->assertEquals(120, $message->validityPeriod); + $this->assertEquals('http://example.com', $message->mediaUrl); + } +} diff --git a/tests/Unit/TwilioSmsMessageTest.php b/tests/Unit/TwilioSmsMessageTest.php new file mode 100644 index 0000000..1e919bc --- /dev/null +++ b/tests/Unit/TwilioSmsMessageTest.php @@ -0,0 +1,77 @@ +message = new TwilioSmsMessage; + } + + /** @test */ + public function it_can_accept_a_message_when_constructing_a_message() + { + $message = new TwilioSmsMessage('myMessage'); + + $this->assertEquals('myMessage', $message->content); + } + + /** @test */ + public function it_provides_a_create_method() + { + $message = TwilioSmsMessage::create('myMessage'); + + $this->assertEquals('myMessage', $message->content); + } + + /** @test */ + public function it_sets_alphanumeric_sender() + { + $message = TwilioSmsMessage::create('myMessage'); + $message->sender('TestSender'); + + $this->assertEquals('TestSender', $message->alphaNumSender); + } + + /** @test */ + public function it_can_return_the_alphanumeric_sender_if_set() + { + $message = TwilioSmsMessage::create('myMessage'); + $message->sender('TestSender'); + + $this->assertEquals('TestSender', $message->getFrom()); + } + + /** @test */ + public function it_can_return_the_messaging_service_sid_if_set() + { + $message = TwilioSmsMessage::create('myMessage'); + $message->messagingServiceSid('TestSid'); + + $this->assertEquals('TestSid', $message->getMessagingServiceSid()); + } + + /** @test */ + public function it_can_set_optional_parameters() + { + $message = TwilioSmsMessage::create('myMessage'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->applicationSid('ABCD1234'); + $message->maxPrice(0.05); + $message->provideFeedback(true); + $message->validityPeriod(120); + + $this->assertEquals('http://example.com', $message->statusCallback); + $this->assertEquals('PUT', $message->statusCallbackMethod); + $this->assertEquals('ABCD1234', $message->applicationSid); + $this->assertEquals(0.05, $message->maxPrice); + $this->assertEquals(true, $message->provideFeedback); + $this->assertEquals(120, $message->validityPeriod); + } +} diff --git a/tests/Unit/TwilioTest.php b/tests/Unit/TwilioTest.php new file mode 100644 index 0000000..53dde58 --- /dev/null +++ b/tests/Unit/TwilioTest.php @@ -0,0 +1,323 @@ +twilioService = Mockery::mock(TwilioService::class); + $this->dispatcher = Mockery::mock(Dispatcher::class); + $this->config = Mockery::mock(TwilioConfig::class); + + $this->twilioService->messages = Mockery::mock(MessageList::class); + $this->twilioService->calls = Mockery::mock(CallList::class); + + $this->twilio = new Twilio($this->twilioService, $this->config); + } + + /** @test */ + public function it_can_send_a_sms_message_to_twilio() + { + $message = new TwilioSmsMessage('Message text'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->applicationSid('ABCD1234'); + $message->maxPrice(0.05); + $message->provideFeedback(true); + $message->validityPeriod(120); + + $this->config->shouldReceive('getFrom') + ->once() + ->andReturn('+1234567890'); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn(null); + + $this->config->shouldReceive('isShortenUrlsEnabled') + ->once() + ->andReturn(false); + + $this->config->shouldReceive('getServiceSid') + ->once() + ->andReturn(null); + + $this->twilioService->messages->shouldReceive('create') + ->atLeast()->once() + ->with('+1111111111', [ + 'from' => '+1234567890', + 'body' => 'Message text', + 'statusCallback' => 'http://example.com', + 'statusCallbackMethod' => 'PUT', + 'applicationSid' => 'ABCD1234', + 'maxPrice' => 0.05, + 'provideFeedback' => true, + 'validityPeriod' => 120, + ]) + ->andReturn(Mockery::mock(MessageInstance::class)); + + $this->twilio->sendMessage($message, '+1111111111'); + } + + /** @test */ + public function it_can_send_a_mms_message_to_twilio() + { + $message = new TwilioMmsMessage('Message text'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->applicationSid('ABCD1234'); + $message->maxPrice(0.05); + $message->provideFeedback(true); + $message->validityPeriod(120); + $message->mediaUrl('http://example.com'); + + $this->config->shouldReceive('getFrom') + ->once() + ->andReturn('+1234567890'); + + $this->config->shouldReceive('isShortenUrlsEnabled') + ->once() + ->andReturn(false); + + $this->config->shouldReceive('getServiceSid') + ->once() + ->andReturn(null); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn(null); + + $this->twilioService->messages->shouldReceive('create') + ->atLeast()->once() + ->with('+1111111111', [ + 'from' => '+1234567890', + 'body' => 'Message text', + 'statusCallback' => 'http://example.com', + 'statusCallbackMethod' => 'PUT', + 'applicationSid' => 'ABCD1234', + 'maxPrice' => 0.05, + 'provideFeedback' => true, + 'validityPeriod' => 120, + 'mediaUrl' => 'http://example.com', + ]) + ->andReturn(Mockery::mock(MessageInstance::class)); + + $this->twilio->sendMessage($message, '+1111111111'); + } + + /** @test */ + public function it_can_send_a_sms_message_to_twilio_with_alphanumeric_sender() + { + $message = new TwilioSmsMessage('Message text'); + + $this->config->shouldReceive('getAlphanumericSender') + ->once() + ->andReturn('TwilioTest'); + + $this->config->shouldNotReceive('getFrom'); + + $this->config->shouldReceive('isShortenUrlsEnabled') + ->once() + ->andReturn(false); + + $this->config->shouldReceive('getServiceSid') + ->once() + ->andReturn(null); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn(null); + + $this->twilioService->messages->shouldReceive('create') + ->atLeast()->once() + ->with('+1111111111', [ + 'from' => 'TwilioTest', + 'body' => 'Message text', + ]) + ->andReturn(Mockery::mock(MessageInstance::class)); + + $this->twilio->sendMessage($message, '+1111111111', true); + } + + /** @test */ + public function it_can_send_a_sms_message_to_twilio_with_messaging_service() + { + $message = new TwilioSmsMessage('Message text'); + + $this->config->shouldReceive('getFrom') + ->once() + ->andReturn('+1234567890'); + + $this->config->shouldReceive('isShortenUrlsEnabled') + ->once() + ->andReturn(false); + + $this->config->shouldReceive('getServiceSid') + ->once() + ->andReturn('service_sid'); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn(null); + + $this->twilioService->messages->shouldReceive('create') + ->atLeast()->once() + ->with('+1111111111', [ + 'from' => '+1234567890', + 'body' => 'Message text', + 'messagingServiceSid' => 'service_sid', + ]) + ->andReturn(Mockery::mock(MessageInstance::class)); + + $this->twilio->sendMessage($message, '+1111111111'); + } + + /** @test */ + public function it_can_send_a_call_to_twilio() + { + $message = new TwilioCallMessage('http://example.com'); + $message->from = '+2222222222'; + $message->status(TwilioCallMessage::STATUS_CANCELED); + $message->method('PUT'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->fallbackUrl('http://example.com'); + $message->fallbackMethod('PUT'); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn('+1111111111'); + + $this->twilioService->calls->shouldReceive('create') + ->atLeast()->once() + ->with('+1111111111', '+2222222222', [ + 'url' => 'http://example.com', + 'status' => TwilioCallMessage::STATUS_CANCELED, + 'method' => 'PUT', + 'statusCallback' => 'http://example.com', + 'statusCallbackMethod' => 'PUT', + 'fallbackUrl' => 'http://example.com', + 'fallbackMethod' => 'PUT', + ]) + ->andReturn(Mockery::mock(CallInstance::class)); + + $this->twilio->sendMessage($message, '+1111111111'); + } + + /** @test */ + public function it_will_throw_an_exception_in_case_of_a_missing_from_number() + { + $this->expectException(CouldNotSendNotification::class); + $this->expectExceptionMessage('Notification was not sent. Missing `from` number.'); + + $smsMessage = new TwilioSmsMessage('Message text'); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn(null); + + $this->config->shouldReceive('getFrom') + ->once() + ->andReturn(null); + + $this->config->shouldReceive('isShortenUrlsEnabled') + ->once() + ->andReturn(false); + + $this->config->shouldReceive('getServiceSid') + ->once() + ->andReturn(null); + + $this->twilio->sendMessage($smsMessage, null); + } + + /** @test */ + public function it_will_throw_an_exception_in_case_of_an_unrecognized_message_object() + { + $this->expectException(CouldNotSendNotification::class); + $this->expectExceptionMessage('Notification was not sent. Message object class'); + + $this->twilio->sendMessage(new InvalidMessage, null); + } + + /** @test */ + public function it_should_use_universal_to() + { + $debugTo = '+1222222222'; + + $message = new TwilioSmsMessage('Message text'); + $message->statusCallback('http://example.com'); + $message->statusCallbackMethod('PUT'); + $message->applicationSid('ABCD1234'); + $message->maxPrice(0.05); + $message->provideFeedback(true); + $message->validityPeriod(120); + + $this->config->shouldReceive('getFrom') + ->once() + ->andReturn('+1234567890'); + + $this->config->shouldReceive('getDebugTo') + ->once() + ->andReturn($debugTo); + + $this->config->shouldReceive('isShortenUrlsEnabled') + ->once() + ->andReturn(false); + + $this->config->shouldReceive('getServiceSid') + ->once() + ->andReturn(null); + + $this->twilioService->messages->shouldReceive('create') + ->atLeast()->once() + ->with($debugTo, [ + 'from' => '+1234567890', + 'body' => 'Message text', + 'statusCallback' => 'http://example.com', + 'statusCallbackMethod' => 'PUT', + 'applicationSid' => 'ABCD1234', + 'maxPrice' => 0.05, + 'provideFeedback' => true, + 'validityPeriod' => 120, + ]) + ->andReturn(Mockery::mock(MessageInstance::class)); + + $this->twilio->sendMessage($message, '+1111111111'); + } +} + +class InvalidMessage extends TwilioMessage {}