SendTestNotificationCommand::handle()   B
last analyzed

Complexity

Conditions 6
Paths 27

Size

Total Lines 42
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 28
c 1
b 0
f 1
dl 0
loc 42
rs 8.8497
cc 6
nc 27
nop 1
1
<?php
2
3
namespace Usamamuneerchaudhary\Notifier\Commands;
4
5
use Illuminate\Console\Command;
6
use Usamamuneerchaudhary\Notifier\Services\NotifierManager;
7
8
class SendTestNotificationCommand extends Command
9
{
10
    protected $signature = 'notifier:test
11
                            {event : The event key to trigger}
12
                            {--user=1 : User ID to send to}
13
                            {--channel=email : Channel to use (email, smack, sms)}
14
                            {--data=* : Additional data to pass to the notification}';
15
16
    protected $description = 'Send a test notification';
17
18
    public function handle(NotifierManager $notifier)
19
    {
20
        $eventKey = $this->argument('event');
21
        $userId = $this->option('user');
22
        $channel = $this->option('channel');
23
        $data = $this->option('data');
24
25
        $notificationData = [];
26
        foreach ($data as $item) {
27
            if (str_contains($item, '=')) {
28
                [$key, $value] = explode('=', $item, 2);
29
                $notificationData[$key] = $value;
30
            }
31
        }
32
33
        $userModel = config('auth.providers.users.model');
34
        $user = $userModel::find($userId);
35
36
        if (!$user) {
37
            $this->error("User with ID {$userId} not found.");
38
            return 1;
39
        }
40
41
        $this->info("Sending test notification...");
42
        $this->info("Event: {$eventKey}");
43
        $this->info("User: {$user->name} ({$user->email})");
44
        $this->info("Channel: {$channel}");
45
46
        if (!empty($notificationData)) {
47
            $this->info("Data: " . json_encode($notificationData));
48
        }
49
50
        try {
51
            $notifier->send($user, $eventKey, $notificationData);
52
53
            $this->info('✅ Test notification sent successfully!');
54
            $this->info('Check the notifier_notifications table to see the result.');
55
56
            return 0;
57
        } catch (\Exception $e) {
58
            $this->error('❌ Failed to send test notification: ' . $e->getMessage());
59
            return 1;
60
        }
61
    }
62
}
63