OneSignalService::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 4
rs 9.9
1
<?php
2
3
namespace Level51\OneSignal;
4
5
use Nyholm\Psr7\Factory\Psr17Factory;
6
use OneSignal\Config;
7
use OneSignal\OneSignal;
8
use SilverStripe\Core\Config\Configurable;
9
use SilverStripe\Core\Environment;
10
use SilverStripe\Core\Injector\Injectable;
11
use Symfony\Component\HttpClient\Psr18Client;
12
13
/**
14
 * Class OneSignalService
15
 *
16
 * @see https://github.com/norkunas/onesignal-php-api
17
 */
18
class OneSignalService
19
{
20
    use Injectable;
21
    use Configurable;
22
23
    /**
24
     * @var OneSignal
25
     */
26
    private $oneSignalClient;
27
28
    /**
29
     * Initializes OneSignal client with env and config vars.
30
     *
31
     * @throws OneSignalException
32
     */
33 4
    public function __construct()
34
    {
35 4
        if (!$appAuthKey = Environment::getEnv('ONESIGNAL_APP_AUTH_KEY')) {
36 1
            throw new OneSignalException(
37 1
                'Missing OneSignal app auth key. Must be an env var "ONESIGNAL_APP_AUTH_KEY".'
38
            );
39
        }
40
41 3
        if (!$authKey = Environment::getEnv('ONESIGNAL_AUTH_KEY')) {
42 1
            throw new OneSignalException('Missing OneSignal auth key. Must be an env var "ONESIGNAL_AUTH_KEY".');
43
        }
44
45 2
        if (!$appId = self::config()->get('app_id')) {
46 1
            throw new OneSignalException('Missing OneSignal app id. Must be a config var "app_id".');
47
        }
48
49 1
        $config = new Config($appId, $appAuthKey, $authKey);
50 1
        $httpClient = new Psr18Client();
51 1
        $requestFactory = $streamFactory = new Psr17Factory();
52
53 1
        $this->oneSignalClient = new OneSignal($config, $httpClient, $requestFactory, $streamFactory);
54 1
    }
55
56
    /**
57
     * Creates and sends a notification.
58
     *
59
     * @see https://documentation.onesignal.com/reference/create-notification#create-notification
60
     *
61
     * @param Notification $notification
62
     *
63
     * @return NotificationResponse
64
     */
65 1
    public function createNotification(Notification $notification)
66
    {
67 1
        $rawResponsePayload = $this->oneSignalClient->notifications()->add($notification->toArray());
68
69 1
        return new NotificationResponse($rawResponsePayload);
70
    }
71
}
72