Passed
Push — master ( 284e72...816a06 )
by Iman
04:12
created

GoogleFCM::send()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
nc 2
nop 2
dl 0
loc 10
c 0
b 0
f 0
cc 3
rs 9.4285
1
<?php
2
3
namespace crocodicstudio\crudbooster\helpers;
4
5
use crocodicstudio\crudbooster\Modules\SettingModule\SettingRepo;
6
7
class GoogleFCM
8
{
9
    private $url = 'https://fcm.googleapis.com/fcm/send';
10
    
11
    public function send($regID, $data)
12
    {
13
        if (! $data['title'] || ! $data['content']) {
14
            return 'title , content null !';
15
        }
16
17
        $fields = $this->getFields($regID, $data);
18
        $headers = $this->getHeaders();
19
20
        return $this->sendRequest($headers, $fields);
21
    }
22
23
    /**
24
     * @param $headers
25
     * @param $fields
26
     * @return mixed
27
     */
28
    private function sendRequest($headers, $fields)
29
    {
30
        $ch = curl_init($this->url);
31
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
32
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
33
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
34
        curl_setopt($ch, CURLOPT_POST, 1);
35
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
36
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
37
        $chresult = curl_exec($ch);
38
        curl_close($ch);
39
40
        return $chresult;
41
    }
42
43
    /**
44
     * @param $regID
45
     * @param $data
46
     * @return array
47
     */
48
    private function getFields($regID, $data)
49
    {
50
        $fields = [
51
            'registration_ids' => $regID,
52
            'data' => $data,
53
            'content_available' => true,
54
            'notification' => [
55
                'sound' => 'default',
56
                'badge' => 0,
57
                'title' => trim(strip_tags($data['title'])),
58
                'body' => trim(strip_tags($data['content'])),
59
            ],
60
            'priority' => 'high',
61
        ];
62
63
        return $fields;
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    private function getHeaders()
70
    {
71
        $apikey = SettingRepo::getSetting('google_fcm_key');
72
        $headers = [
73
            'Authorization:key='.$apikey,
74
            'Content-Type:application/json',
75
        ];
76
77
        return $headers;
78
    }
79
}