Skip to content

Commit f937284

Browse files
committed
Add support to attach json data to the notification message.
1 parent cc2f594 commit f937284

File tree

3 files changed

+58
-4
lines changed

3 files changed

+58
-4
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
namespace NotificationChannels\ExpoPushNotifications\Exceptions;
4+
5+
class CouldNotCreateMessage extends \Exception
6+
{
7+
}

src/ExpoMessage.php

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace NotificationChannels\ExpoPushNotifications;
44

5+
use NotificationChannels\ExpoPushNotifications\Exceptions\CouldNotCreateMessage;
6+
57
class ExpoMessage
68
{
79
/**
@@ -34,6 +36,15 @@ class ExpoMessage
3436
protected $ttl = 0;
3537

3638
/**
39+
* The json data attached to the message.
40+
*
41+
* @var string
42+
*/
43+
protected $jsonData = '';
44+
45+
/**
46+
* Create a message with given body.
47+
*
3748
* @param string $body
3849
*
3950
* @return static
@@ -119,6 +130,33 @@ public function setTtl(int $ttl)
119130
return $this;
120131
}
121132

133+
/**
134+
* Set the json Data attached to the message.
135+
*
136+
* @param array|string $data
137+
*
138+
* @return $this
139+
*
140+
* @throws CouldNotCreateMessage
141+
*/
142+
public function setJsonData($data)
143+
{
144+
if (is_array($data)) {
145+
$data = json_encode($data);
146+
}
147+
elseif (is_string($data)) {
148+
@json_decode($data);
149+
150+
if (json_last_error() !== JSON_ERROR_NONE) {
151+
throw new CouldNotCreateMessage('Invalid json format passed to the setJsonData().');
152+
}
153+
}
154+
155+
$this->jsonData = $data;
156+
157+
return $this;
158+
}
159+
122160
/**
123161
* Get an array representation of the message.
124162
*
@@ -127,10 +165,11 @@ public function setTtl(int $ttl)
127165
public function toArray()
128166
{
129167
return [
130-
'body' => $this->body,
131-
'sound' => $this->sound,
132-
'badge' => $this->badge,
133-
'ttl' => $this->ttl,
168+
'body' => $this->body,
169+
'sound' => $this->sound,
170+
'badge' => $this->badge,
171+
'ttl' => $this->ttl,
172+
'jsonData' => $this->jsonData,
134173
];
135174
}
136175
}

tests/MessageTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,12 @@ public function itCanSetTimeToLive()
9090

9191
$this->assertEquals(60, Arr::get($this->message->toArray(), 'ttl'));
9292
}
93+
94+
/** @test */
95+
public function itCanSetJSONData()
96+
{
97+
$this->message->setJsonData('{"name":"Aly"}');
98+
99+
$this->assertEquals('{"name":"Aly"}', Arr::get($this->message->toArray(), 'jsonData'));
100+
}
93101
}

0 commit comments

Comments
 (0)