Completed
Branch master (431168)
by Gennady
09:40
created

Message::jsonSerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * PHP APNS.
4
 *
5
 * @author Gennady Telegin <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Apns;
12
13
/**
14
 * Class Message.
15
 *
16
 * @see https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1
17
 */
18
class Message implements \JsonSerializable
19
{
20
    const PRIORITY_IMMEDIATELY = 10;
21
    const PRIORITY_SOMETIMES = 5;
22
23
    /**
24
     * Custom data for the APS body.
25
     *
26
     * @var array
27
     */
28
    protected $customData = [];
29
30
    /**
31
     * Device identifier.
32
     *
33
     * @var string
34
     */
35
    protected $identifier;
36
37
    /**
38
     * The APS core body.
39
     *
40
     * @var array
41
     */
42
    protected $apsBody = [];
43
44
    /**
45
     * A canonical UUID that identifies the notification.
46
     *
47
     * @var string
48
     */
49
    protected $id;
50
51
    /**
52
     * Expiration date (UTC).
53
     *
54
     * A UNIX epoch date expressed in seconds (UTC).
55
     * This header identifies the date when the notification is no longer valid and can be discarded.
56
     * If this value is nonzero, APNs stores the notification and tries to deliver it at least once,
57
     * repeating the attempt as needed if it is unable to deliver the notification the first time.
58
     * If the value is 0, APNs treats the notification as if it expires immediately and
59
     * does not store the notification or attempt to redeliver it.
60
     *
61
     * @var int
62
     */
63
    protected $expiry = 0;
64
65
    /**
66
     * The priority of the notification. Specify one of the following values:
67
     *  - 10 – Send the push message immediately. Notifications with this priority must trigger an alert, sound,
68
     *         or badge on the target device. It is an error to use this priority for a push notification
69
     *         that contains only the content-available key.
70
     *  -  5 — Send the push message at a time that takes into account power considerations for the device.
71
     *         Notifications with this priority might be grouped and delivered in bursts. They are throttled,
72
     *         and in some cases are not delivered.
73
     * If you omit this header, the APNs server sets the priority to 10.
74
     *
75
     * @var int
76
     */
77
    protected $priority;
78
79
    /**
80
     * @var string
81
     */
82
    protected $topic;
83
84
    /**
85
     * Class constructor.
86
     */
87 20
    public function __construct($identifier = null)
88
    {
89 20
        $this->apsBody = [
90 20
            'aps' => [],
91
        ];
92
93 20
        if (null !== $identifier) {
94 1
            $this->identifier = $identifier;
95 1
        }
96 20
    }
97
98
    /**
99
     * Gets the full message body to send to APN.
100
     *
101
     * @return array
102
     */
103 10
    public function jsonSerialize()
104
    {
105 10
        $payloadBody = $this->apsBody;
106
107 10
        if (!empty($this->customData)) {
108 3
            $payloadBody = array_merge($payloadBody, $this->customData);
109 3
        }
110
111 10
        return $payloadBody;
112
    }
113
114
    /**
115
     * Gets the apns-* headers to send in requrest to APN.
116
     *
117
     * @return array
118
     */
119 4
    public function getMessageHeaders()
120
    {
121 4
        $headers = [];
122 4
        if ($this->id) {
123 1
            $headers['apns-id'] = $this->id;
124 1
        }
125 4
        if ($this->expiry) {
126 1
            $headers['apns-expiration'] = $this->expiry;
127 1
        }
128 4
        if ($this->priority) {
129 1
            $headers['apns-priority'] = $this->priority;
130 1
        }
131 4
        if ($this->topic) {
132 1
            $headers['apns-topic'] = $this->topic;
133 1
        }
134
135 4
        return $headers;
136
    }
137
138
    /**
139
     * Sets the alert title. For iOS, this is the APS alert message.
140
     *
141
     * @param MessageAlert|string $alert
142
     *
143
     * @return self
144
     *
145
     * @throws \InvalidArgumentException
146
     */
147 3
    public function setAlert($alert)
148
    {
149 3
        if (!is_string($alert) && !$alert instanceof MessageAlert) {
150 1
            throw new \InvalidArgumentException(
151 1
                sprintf(
152 1
                    'Messages alert must be either string or instance of MessageAlert. Instance of "%s" provided',
153 1
                    gettype($alert)
154 1
                )
155 1
            );
156
        }
157
158 2
        $this->apsBody['aps']['alert'] = $alert;
159
160 2
        return $this;
161
    }
162
163
    /**
164
     * Sets any custom data for the APS body.
165
     *
166
     * @param array $data
167
     *
168
     * @return self
169
     */
170 1
    public function setData(array $data)
171
    {
172 1
        if (array_key_exists('aps', $data)) {
173 1
            unset($data['aps']);
174 1
        }
175
176 1
        foreach ($data as $key => $value) {
177 1
            $this->addCustomData($key, $value);
178 1
        }
179
180 1
        return $this;
181
    }
182
183
    /**
184
     * Add custom data.
185
     *
186
     * @param string $key
187
     * @param mixed  $value
188
     *
189
     * @return self
190
     *
191
     * @throws \LogicException
192
     * @throws \InvalidArgumentException
193
     */
194 5
    public function addCustomData($key, $value)
195
    {
196 5
        if ('aps' == $key) {
197 1
            throw new \LogicException('Can\'t replace "aps" data. Please call to setAlert, if your want replace message text.');
198
        }
199
200 4
        if (is_object($value)) {
201 2
            if (!$value instanceof \stdClass && !$value instanceof \JsonSerializable) {
202 1
                throw new \InvalidArgumentException(sprintf(
203 1
                    'Object %s must be implements JsonSerializable interface for next serialize data.',
204 1
                    get_class($value)
205 1
                ));
206
            }
207 1
        }
208
209 3
        $this->customData[$key] = $value;
210
211 3
        return $this;
212
    }
213
214
    /**
215
     * Sets the identifier of the target device, eg UUID or similar.
216
     *
217
     * @param string $identifier
218
     *
219
     * @return self
220
     */
221 1
    public function setDeviceIdentifier($identifier)
222
    {
223 1
        $this->identifier = $identifier;
224
225 1
        return $this;
226
    }
227
228
    /**
229
     * Returns the device identifier.
230
     *
231
     * @return null|string
232
     */
233 3
    public function getDeviceIdentifier()
234
    {
235 3
        return $this->identifier;
236
    }
237
238
    /**
239
     * iOS-specific
240
     * Sets the APS sound.
241
     *
242
     * @param string $sound The sound to use. Use 'default' to use the built-in default
243
     *
244
     * @return self
245
     */
246 1
    public function setAPSSound($sound)
247
    {
248 1
        $this->apsBody['aps']['sound'] = (string) $sound;
249
250 1
        return $this;
251
    }
252
253
    /**
254
     * iOS-specific
255
     * Sets the APS badge count.
256
     *
257
     * @param int $badge The badge count to display
258
     *
259
     * @return self
260
     */
261 1
    public function setAPSBadge($badge)
262
    {
263 1
        $this->apsBody['aps']['badge'] = (int) $badge;
264
265 1
        return $this;
266
    }
267
268
    /**
269
     * Sets the APS content available flag.
270
     * This flag means that when your app is launched in the background or resumed,
271
     * application:didReceiveRemoteNotification:fetchCompletionHandler: is called.
272
     *
273
     * @param string $contentAvailable The flag to set the content-available option, only 1 or null.
274
     *
275
     * @return self
276
     */
277 1
    public function setAPSContentAvailable($contentAvailable = null)
278
    {
279 1
        if (1 === $contentAvailable) {
280 1
            $this->apsBody['aps']['content-available'] = 1;
281 1
        } else {
282 1
            unset($this->apsBody['aps']['content-available']);
283
        }
284
285 1
        return $this;
286
    }
287
288
    /**
289
     * Sets the APS category.
290
     *
291
     * @param string $category The notification category
292
     */
293 1
    public function setAPSCategory($category)
294
    {
295 1
        $this->apsBody['aps']['category'] = (string) $category;
296 1
    }
297
298
    /**
299
     * Get apns-id of message.
300
     *
301
     * @return string
302
     */
303 1
    public function getId()
304
    {
305 1
        return $this->id;
306
    }
307
308
    /**
309
     * Set apns-id of message.
310
     *
311
     * @param string $id
312
     *
313
     * @return self
314
     */
315 1
    public function setId($id)
316
    {
317 1
        $this->id = (string) $id;
318
319 1
        return $this;
320
    }
321
322
    /**
323
     * Get expiry of message.
324
     *
325
     * @return int
326
     */
327 1
    public function getExpiry()
328
    {
329 1
        return $this->expiry;
330
    }
331
332
    /**
333
     * Set expiry of message.
334
     *
335
     * @param int $expiry
336
     *
337
     * @return self
338
     */
339 1
    public function setExpiry($expiry)
340
    {
341 1
        $this->expiry = (int) $expiry;
342
343 1
        return $this;
344
    }
345
346
    /**
347
     * @return int
348
     */
349 1
    public function getPriority()
350
    {
351 1
        return $this->priority;
352
    }
353
354
    /**
355
     * @param int $priority
356
     *
357
     * @return self
358
     */
359 1
    public function setPriority($priority)
360
    {
361 1
        $this->priority = (int) $priority;
362
363 1
        return $this;
364
    }
365
366
    /**
367
     * Get apns-topic of message.
368
     *
369
     * @return string
370
     */
371 1
    public function getTopic()
372
    {
373 1
        return $this->topic;
374
    }
375
376
    /**
377
     * Set apns-topic of message.
378
     *
379
     * @param string $topic
380
     *
381
     * @return self
382
     */
383 1
    public function setTopic($topic)
384
    {
385 1
        $this->topic = (string) $topic;
386
387 1
        return $this;
388
    }
389
}
390