Passed
Pull Request — master (#6421)
by Yannick
27:19 queued 14:40
created

PushNotificationHelper::sendNotification()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 24
nc 4
nop 4
dl 0
loc 38
rs 8.9137
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chamilo\CoreBundle\Helpers;
6
7
use Chamilo\CoreBundle\Entity\User;
8
use Chamilo\CoreBundle\Repository\PushSubscriptionRepository;
9
use Chamilo\CoreBundle\Settings\SettingsManager;
10
use Symfony\Component\HttpClient\HttpClient;
11
12
class PushNotificationHelper
13
{
14
    public function __construct(
15
        private readonly PushSubscriptionRepository $subscriptionRepository,
16
        private readonly SettingsManager $settingsManager
17
    ) {
18
    }
19
20
    public function sendNotification(User $user, string $title, string $message, string $url = '/'): void
21
    {
22
        $settings = $this->settingsManager->getSetting('platform.push_notification_settings');
23
24
        if (empty($settings)) {
25
            return;
26
        }
27
28
        $decoded = json_decode($settings, true);
29
30
        $gotifyUrl = $decoded['gotify_url'] ?? null;
31
        $gotifyToken = $decoded['gotify_token'] ?? null;
32
        $enabled = $decoded['enabled'] ?? false;
33
34
        if (!$enabled || empty($gotifyUrl) || empty($gotifyToken)) {
35
            return;
36
        }
37
38
        $subscriptions = $this->subscriptionRepository->findByUser($user);
39
40
        if (empty($subscriptions)) {
41
            return;
42
        }
43
44
        $client = HttpClient::create();
45
46
        $client->request('POST', $gotifyUrl.'/message', [
47
            'headers' => [
48
                'X-Gotify-Key' => $gotifyToken,
49
            ],
50
            'json' => [
51
                'title' => $title,
52
                'message' => $message,
53
                'priority' => 5,
54
                'extras' => [
55
                    'client::notification' => [
56
                        'click' => [
57
                            'url' => $url,
58
                        ],
59
                    ],
60
                ],
61
            ],
62
        ]);
63
    }
64
}
65