GcmComponent::sendData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 3
1
<?php
2
namespace ker0x\CakeGcm\Controller\Component;
3
4
use Cake\Controller\Component;
5
use Cake\Controller\ComponentRegistry;
6
use Cake\Network\Http\Client;
7
use Cake\Utility\Hash;
8
use \Exception;
9
10
/**
11
 * Gcm Component
12
 *
13
 */
14
class GcmComponent extends Component
15
{
16
17
    /**
18
     * Default config
19
     *
20
     * @var array
21
     */
22
    protected $_defaultConfig = [
23
        'api' => [
24
            'key' => null,
25
            'url' => 'https://gcm-http.googleapis.com/gcm/send'
26
        ],
27
        'parameters' => [
28
            'collapse_key' => null,
29
            'priority' => 'normal',
30
            'delay_while_idle' => false,
31
            'dry_run' => false,
32
            'time_to_live' => 0,
33
            'restricted_package_name' => null
34
        ],
35
        'http' => []
36
    ];
37
38
    /**
39
     * List of parameters available to use in notification messages.
40
     *
41
     * @var array
42
     */
43
    protected $_allowedNotificationParameters = [
44
        'title',
45
        'body',
46
        'icon',
47
        'sound',
48
        'badge',
49
        'tag',
50
        'color',
51
        'click_action',
52
        'body_loc_key',
53
        'body_loc_args',
54
        'title_loc_key',
55
        'title_loc_args'
56
    ];
57
58
    /**
59
     * Error code and message.
60
     *
61
     * @var array
62
     */
63
    protected $_errorMessages = [];
64
65
    /**
66
     * Response of the request
67
     *
68
     * @var object
69
     */
70
    protected $_response = null;
71
72
    /**
73
     * Constructor
74
     *
75
     * @param ComponentRegistry $registry A ComponentRegistry
76
     * @param array $config Array of configuration settings
77
     */
78
    public function __construct(ComponentRegistry $registry, array $config = [])
79
    {
80
        parent::__construct($registry, $config);
81
        $this->_errorMessages = [
82
            '400' => __('Error 400. The request could not be parsed as JSON.'),
83
            '401' => __('Error 401. Unable to authenticating the sender account.'),
84
            '500' => __('Error 500. Internal Server Error.'),
85
            '503' => __('Error 503. Service Unavailable.')
86
        ];
87
    }
88
89
    /**
90
     * Send a downstream message to one or more devices
91
     *
92
     * @param mixed $ids Devices'ids
93
     * @param array $payload The notification and/or some datas
94
     * @param array $parameters Parameters for the GCM request
95
     * @throws Exception
96
     * @return bool
97
     */
98
    public function send($ids = null, array $payload = [], array $parameters = [])
99
    {
100
        $ids = $this->_checkIds($ids);
101
102
        if (!is_array($payload)) {
103
            throw new Exception(__('Payload must be an array.'));
104
        }
105
106
        if (isset($payload['notification'])) {
107
            $payload['notification'] = $this->_checkNotification($payload['notification']);
108
        }
109
110
        if (isset($payload['data'])) {
111
            $payload['data'] = $this->_checkData($payload['data']);
112
        }
113
114
        $parameters = $this->_checkParameters($parameters);
115
116
        $message = $this->_buildMessage($ids, $payload, $parameters);
117
118
        return $this->_executePush($message);
119
    }
120
121
    /**
122
     * Shortcut to send notification
123
     *
124
     * @param mixed $ids Devices'ids
125
     * @param array $notification The notification
126
     * @param array $parameters Parameters for the GCM request
127
     * @return bool
128
     */
129
    public function sendNotification($ids = null, array $notification = [], array $parameters = [])
130
    {
131
        return $this->send($ids, ['notification' => $notification], $parameters);
132
    }
133
134
    /**
135
     * Shortcut to send datas
136
     *
137
     * @param mixed $ids Devices'ids
138
     * @param array $data Some datas
139
     * @param array $parameters Parameters for the GCM request
140
     * @return bool
141
     */
142
    public function sendData($ids = null, array $data = [], array $parameters = [])
143
    {
144
        return $this->send($ids, ['data' => $data], $parameters);
145
    }
146
147
    /**
148
     * Return the response of the push
149
     *
150
     * @return string
151
     */
152
    public function response()
153
    {
154
        if (array_key_exists($this->_response->code, $this->_errorMessages)) {
155
            return $this->_errorMessages[$this->_response->code];
156
        }
157
158
        return json_decode($this->_response->body, true);
159
    }
160
161
    /**
162
     * Send the message throught a POST request to the GCM servers
163
     *
164
     * @param string $message The message to send
165
     * @throws Exception
166
     * @return bool
167
     */
168
    protected function _executePush($message)
169
    {
170
        $options = $this->_getHttpOptions();
171
172
        $http = new Client();
173
        $this->_response = $http->post($this->config('api.url'), $message, $options);
174
175
        return ($this->_response->code === '200') ? true : false;
176
    }
177
178
    /**
179
     * Build the message from the ids, payload and parameters
180
     *
181
     * @param array|string $ids Devices'ids
182
     * @param array $payload The notification and/or some datas
183
     * @param array $parameters Parameters for the GCM request
184
     * @return string
185
     */
186
    protected function _buildMessage($ids, $payload, $parameters)
187
    {
188
        $message = (count($ids) > 1) ? ['registration_ids' => $ids] : ['to' => current($ids)];
189
190
        if (!empty($payload)) {
191
            $message += $payload;
192
        }
193
194
        if (!empty($parameters)) {
195
            $message += $parameters;
196
        }
197
198
        return json_encode($message);
199
    }
200
201
    /**
202
     * Check if the ids are correct
203
     *
204
     * @param mixed $ids Devices'ids
205
     * @throws Exception
206
     * @return array
207
     */
208
    protected function _checkIds($ids)
209
    {
210
        if (is_string($ids)) {
211
            $ids = (array)$ids;
212
        }
213
214
        if (is_null($ids) || !is_array($ids) || empty($ids)) {
215
            throw new Exception(__('Ids must be a string or an array with at least 1 token.'));
216
        }
217
218
        if (is_array($ids) && count($ids) > 1000) {
219
            throw new Exception(__('Ids must contain at least 1 and at most 1000 registration tokens.'));
220
        }
221
222
        return $ids;
223
    }
224
225
    /**
226
     * Check if the notification array is correctly build
227
     *
228
     * @param array $notification The notification
229
     * @throws Exception
230
     * @return array $notification
231
     */
232
    protected function _checkNotification(array $notification = [])
233
    {
234
        if (!is_array($notification)) {
235
            throw new Exception('Notification must be an array.');
236
        }
237
238
        if (empty($notification) || !isset($notification['title'])) {
239
            throw new Exception('Notification\'s array must contain at least a key title.');
240
        }
241
242
        if (!isset($notification['icon'])) {
243
            $notification['icon'] = 'myicon';
244
        }
245
246
        foreach ($notification as $key => $value) {
247
            if (!in_array($key, $this->_allowedNotificationParameters)) {
248
                throw new Exception("The key {$key} is not allowed in notifications.");
249
            }
250
        }
251
252
        return $notification;
253
    }
254
255
    /**
256
     * Check if the data array is correctly build
257
     *
258
     * @param array $data Some datas
259
     * @throws Exception
260
     * @return array $data
261
     */
262
    protected function _checkData(array $data = [])
263
    {
264
        if (!is_array($data)) {
265
            throw new Exception('Data must ba an array.');
266
        }
267
268
        if (empty($data)) {
269
            throw new Exception('Data\'s array can\'t be empty.');
270
        }
271
272
        // Convert all data into string
273
        foreach ($data as $key => $value) {
274
            $data[$key] = (string)$value;
275
        }
276
277
        return $data;
278
    }
279
280
    /**
281
     * Check the parameters for the message
282
     *
283
     * @param array $parameters Parameters for the GCM request
284
     * @throws Exception
285
     * @return array $parameters
286
     */
287
    protected function _checkParameters(array $parameters = [])
288
    {
289
        if (!is_array($parameters)) {
290
            throw new Exception(__('Parameters must be an array.'));
291
        }
292
293
        $parameters = Hash::merge($this->config('parameters'), $parameters);
294
295
        if (isset($parameters['time_to_live']) && !is_int($parameters['time_to_live'])) {
296
            $parameters['time_to_live'] = (int)$parameters['time_to_live'];
297
        }
298
299
        if (isset($parameters['delay_while_idle']) && !is_bool($parameters['delay_while_idle'])) {
300
            $parameters['delay_while_idle'] = (bool)$parameters['delay_while_idle'];
301
        }
302
303
        if (isset($parameters['dry_run']) && !is_bool($parameters['dry_run'])) {
304
            $parameters['dry_run'] = (bool)$parameters['dry_run'];
305
        }
306
307
        return $parameters;
308
    }
309
310
    /**
311
     * Return options for the HTTP request
312
     *
313
     * @throws Exception
314
     * @return array $options
315
     */
316
    protected function _getHttpOptions()
317
    {
318
        if ($this->config('api.key') === null) {
319
            throw new Exception(__('No API key set. Push not triggered'));
320
        }
321
322
        $options = Hash::merge($this->config('http'), [
323
            'type' => 'json',
324
            'headers' => [
325
                'Authorization' => 'key=' . $this->config('api.key'),
326
                'Content-Type' => 'application/json'
327
            ]
328
        ]);
329
330
        return $options;
331
    }
332
}
333