Skip to content

Commit

Permalink
Prepare for Laravel 9 Upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
nickfls committed Jan 19, 2022
1 parent cc31971 commit e5ebd72
Show file tree
Hide file tree
Showing 18 changed files with 184 additions and 98 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
build
.idea/
.phpunit.result.cache
composer.lock
docs
vendor
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ class MyCustomMailgunWebhookJob extends ProcessMailgunWebhookJob
```
### Handling multiple signing secrets

When needed might want to the package to handle multiple endpoints and secrets. Here's how to configurate that behaviour.
When needed might want to the package to handle multiple endpoints and secrets. Here's how to configure that behaviour.

If you are using the `Route::mailgunWebhooks` macro, you can append the `configKey` as follows:

Expand All @@ -259,7 +259,7 @@ Alternatively, if you are manually defining the route, you can add `configKey` l
Route::post('webhooks/mailgun/{configKey}', 'BinaryCats\MailgunWebhooks\MailgunWebhooksController');
```

If this route parameter is present the verify middleware will look for the secret using a different config key, by appending the given the parameter value to the default config key. E.g. If Mailgun posts to `webhooks/mailgun/my-named-secret` you'd add a new config named `signing_secret_my-named-secret`.
If this route parameter is present verify middleware will look for the secret using a different config key, by appending the given the parameter value to the default config key. E.g. If Mailgun posts to `webhooks/mailgun/my-named-secret` you'd add a new config named `signing_secret_my-named-secret`.

Example config might look like:

Expand Down
28 changes: 13 additions & 15 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,42 +18,40 @@
}
],
"require": {
"php": "^7.2|^8.0",
"illuminate/support": "~5.8.0|^6.0|^7.0|^8.0",
"php": "^7.4|^8.0",
"illuminate/support": "^8.0|^9.0",
"spatie/laravel-webhook-client": "^2.0"
},
"require-dev": {
"orchestra/testbench": "~3.8.0|^4.0|^5.0|^6.0",
"phpunit/phpunit": "^8.2|^9.0"
"orchestra/testbench": "^6.0",
"phpunit/phpunit": "^9.3.3"
},
"autoload": {
"psr-4": {
"BinaryCats\\MailgunWebhooks\\": "src"
"BinaryCats\\MailgunWebhooks\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"BinaryCats\\MailgunWebhooks\\Tests\\": "tests"
"Tests\\": "tests/"
}
},
"suggest": {
"binary-cats/laravel-mail-helpers": "^6.0"
},
"scripts": {
"test": "vendor/bin/phpunit --color=always",
"check": [
"php-cs-fixer fix --ansi --dry-run --diff",
"phpcs --report-width=200 --report-summary --report-full src/ tests/ --standard=PSR2 -n",
"phpmd src/,tests/ text ./phpmd.xml.dist"
],
"fix": [
"php-cs-fixer fix --ansi"
]
"analyze": "./vendor/bin/phpstan analyse src --memory-limit=2G",
"coverage": "XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html coverage -d pcov.enabled",
"test": "./vendor/bin/phpunit --color=always -vvv"
},
"config": {
"optimize-autoloader": true,
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "2.x-dev"
},
"laravel": {
"providers": [
"BinaryCats\\MailgunWebhooks\\MailgunWebhooksServiceProvider"
Expand Down
5 changes: 4 additions & 1 deletion config/mailgun-webhooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
* here. The key is the name of the Mailgun event type with the `.` replaced by a `_`.
*
* You can find a list of Mailgun webhook types here:
* https://documentation.mailgun.com/en/latest/api-webhooks.html#webhooks.
* https://documentation.mailgun.com/en/latest/user_manual.html#events.
*
* The package will automatically convert the keys to lowercase, but you should
* be congnisant of the fact that array keys are case sensitive
*/
'jobs' => [
// 'delivered' => \BinaryCats\MailgunWebhooks\Jobs\HandleDelivered::class,
Expand Down
29 changes: 16 additions & 13 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="true"
stopOnFailure="false">
stopOnFailure="false"
verbose="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">src/</directory>
</include>
<report>
<clover outputFile="build/logs/clover.xml"/>
<html outputDirectory="build/coverage"/>
<text outputFile="build/coverage.txt"/>
</report>
</coverage>
<testsuites>
<testsuite name="Binary Cats Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<logging>
<log type="tap" target="build/report.tap"/>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<junit outputFile="build/report.junit.xml"/>
</logging>
</phpunit>
17 changes: 9 additions & 8 deletions src/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,32 @@

use BinaryCats\MailgunWebhooks\Contracts\WebhookEvent;

class Event implements WebhookEvent
final class Event implements WebhookEvent
{
/**
* Attributes from the event.
*
* @var array
* @var mixed[]
*/
public $attributes = [];
public array $attributes = [];

/**
* Create new Event.
*
* @param array $attributes
* @param mixed[] $attributes
*/
public function __construct($attributes)
public function __construct(array $attributes)
{
$this->attributes = $attributes;
}

/**
* Construct the event.
* Static event constructor
*
* @return Event
* @param mixed[] $data
* @return static
*/
public static function constructFrom($data): self
public static function constructFrom(array $data): self
{
return new static($data);
}
Expand Down
4 changes: 4 additions & 0 deletions src/Exceptions/UnexpectedValueException.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

class UnexpectedValueException extends BaseUnexpectedValueException
{
/**
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
*/
public function render($request)
{
return response(['error' => $this->getMessage()], 400);
Expand Down
26 changes: 22 additions & 4 deletions src/Exceptions/WebhookFailed.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,46 @@
use Exception;
use Spatie\WebhookClient\Models\WebhookCall;

class WebhookFailed extends Exception
final class WebhookFailed extends Exception
{
/**
* @return static
*/
public static function invalidSignature(): self
{
return new static('The signature is invalid.');
}

/**
* @return static
*/
public static function signingSecretNotSet(): self
{
return new static('The webhook signing secret is not set. Make sure that the `signing_secret` config key is set to the correct value.');
}

/**
* @param string $jobClass
* @param \Spatie\WebhookClient\Models\WebhookCall $webhookCall
* @return static
*/
public static function jobClassDoesNotExist(string $jobClass, WebhookCall $webhookCall): self
{
return new static("Could not process webhook id `{$webhookCall->id}` of type `{$webhookCall->type} because the configured jobclass `$jobClass` does not exist.");
return new static("Could not process webhook id `{$webhookCall->getKey()}` of type `{$webhookCall->getAttribute('type')} because the configured jobclass `$jobClass` does not exist.");
}

/**
* @param \Spatie\WebhookClient\Models\WebhookCall $webhookCall
* @return static
*/
public static function missingType(WebhookCall $webhookCall): self
{
return new static("Webhook call id `{$webhookCall->id}` did not contain a type. Valid Mailgun webhook calls should always contain a type.");
return new static("Webhook call id `{$webhookCall->getKey()}` did not contain a type. Valid Mailgun webhook calls should always contain a type.");
}

/**
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
*/
public function render($request)
{
return response(['error' => $this->getMessage()], 400);
Expand Down
6 changes: 3 additions & 3 deletions src/Jobs/HandleDelivered.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ class HandleDelivered
/**
* Bind the implementation.
*
* @var Spatie\WebhookClient\Models\WebhookCall
* @var \Spatie\WebhookClient\Models\WebhookCall
*/
protected $webhookCall;
protected WebhookCall $webhookCall;

/**
* Create new Job.
*
* @param Spatie\WebhookClient\Models\WebhookCall $webhookCall
* @param \Spatie\WebhookClient\Models\WebhookCall $webhookCall
*/
public function __construct(WebhookCall $webhookCall)
{
Expand Down
21 changes: 4 additions & 17 deletions src/MailgunSignatureValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,11 @@

class MailgunSignatureValidator implements SignatureValidator
{
/**
* Bind the implemetation.
*
* @var Illuminate\Http\Request
*/
protected $request;

/**
* Inject the config.
*
* @var Spatie\WebhookClient\WebhookConfig
*/
protected $config;

/**
* True if the signature has been valiates.
*
* @param Illuminate\Http\Request $request
* @param Spatie\WebhookClient\WebhookConfig $config
* @param \Illuminate\Http\Request $request
* @param \Spatie\WebhookClient\WebhookConfig $config
*
* @return bool
*/
Expand All @@ -40,6 +26,7 @@ public function isValid(Request $request, WebhookConfig $config): bool
try {
Webhook::constructEvent($request->all(), $signature, $secret);
} catch (Exception $exception) {
// make the app aware
report($exception);

return false;
Expand All @@ -52,7 +39,7 @@ public function isValid(Request $request, WebhookConfig $config): bool
* Validate the incoming signature' schema.
*
* @param \Illuminate\Http\Request $request
* @return array
* @return string[]
*/
protected function signature(Request $request): array
{
Expand Down
4 changes: 1 addition & 3 deletions src/MailgunWebhooksController.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ public function __invoke(Request $request, string $configKey = null)
'process_webhook_job' => config('mailgun-webhooks.process_webhook_job'),
]);

(new WebhookProcessor($request, $webhookConfig))->process();

return response()->json(['message' => 'ok']);
return (new WebhookProcessor($request, $webhookConfig))->process();
}
}
38 changes: 32 additions & 6 deletions src/ProcessMailgunWebhookJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use BinaryCats\MailgunWebhooks\Exceptions\WebhookFailed;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Spatie\WebhookClient\ProcessWebhookJob;

class ProcessMailgunWebhookJob extends ProcessWebhookJob
Expand All @@ -24,29 +25,54 @@ public function handle()
{
$type = Arr::get($this->webhookCall, "payload.{$this->key}");

if (! $type) {
if (!$type) {
throw WebhookFailed::missingType($this->webhookCall);
}

event("mailgun-webhooks::{$type}", $this->webhookCall);
event($this->determineEventKey($type), $this->webhookCall);

$jobClass = $this->determineJobClass($type);

if ($jobClass === '') {
if ('' === $jobClass) {
return;
}

if (! class_exists($jobClass)) {
if (!class_exists($jobClass)) {
throw WebhookFailed::jobClassDoesNotExist($jobClass, $this->webhookCall);
}

dispatch(new $jobClass($this->webhookCall));
}

/**
* @param string $eventType
* @return string
*/
protected function determineJobClass(string $eventType): string
{
$jobConfigKey = str_replace('.', '_', $eventType);
return config($this->determineJobConfigKey($eventType), '');
}

return config("mailgun-webhooks.jobs.{$jobConfigKey}", '');
/**
* @param string $eventType
* @return string
*/
protected function determineJobConfigKey(string $eventType): string
{
return Str::of($eventType)
->replace('.', '_')
->prepend('mailgun-webhooks.jobs.')
->lower();
}

/**
* @param string $eventType
* @return string
*/
protected function determineEventKey(string $eventType): string
{
return Str::of($eventType)
->prepend('mailgun-webhooks::')
->lower();
}
}
Loading

0 comments on commit e5ebd72

Please sign in to comment.