Add a listener to automatically log notification sends

This commit is contained in:
Bubka 2024-02-26 15:04:47 +01:00
parent 1e42008be7
commit 04078b09aa
4 changed files with 69 additions and 2 deletions

View File

@ -0,0 +1,35 @@
<?php
namespace App\Listeners;
use Illuminate\Notifications\Events\NotificationSent;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class LogNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @return void
*/
public function handle(NotificationSent $event)
{
// $event->channel
// $event->notifiable
// $event->notification
// $event->response
Log::info(sprintf('Notification of type %s sent via channel %s to user ID #%s', get_class($event->notification), $event->channel, $event->notifiable->id));
}
}

View File

@ -131,8 +131,6 @@ class User extends Authenticatable implements WebAuthnAuthenticatable
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
Log::info(sprintf('Password reset token sent to user id "%s', $this->id));
}
/**

View File

@ -8,6 +8,7 @@ use App\Events\ScanForNewReleaseCalled;
use App\Events\TwoFAccountDeleted;
use App\Listeners\CleanIconStorage;
use App\Listeners\DissociateTwofaccountFromGroup;
use App\Listeners\LogNotification;
use App\Listeners\RegisterOpenId;
use App\Listeners\ReleaseRadar;
use App\Listeners\ResetUsersPreference;
@ -16,6 +17,7 @@ use App\Observers\UserObserver;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Notifications\Events\NotificationSent;
use SocialiteProviders\Manager\SocialiteWasCalled;
class EventServiceProvider extends ServiceProvider
@ -44,6 +46,9 @@ class EventServiceProvider extends ServiceProvider
SocialiteWasCalled::class => [
RegisterOpenId::class,
],
NotificationSent::class => [
LogNotification::class,
],
];
/**

View File

@ -0,0 +1,29 @@
<?php
namespace Tests\Unit\Listeners;
use App\Listeners\LogNotification;
use Illuminate\Notifications\Events\NotificationSent;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\CoversClass;
use Tests\TestCase;
/**
* ResetUsersPreferenceTest test class
*/
#[CoversClass(LogNotification::class)]
class LogNotificationTest extends TestCase
{
/**
* @test
*/
public function test_LogNotificationTest_listen_to_NotificationSent_event()
{
Event::fake();
Event::assertListening(
NotificationSent::class,
LogNotification::class
);
}
}