Skip to content

Commit 504a7ec

Browse files
authored
Merge pull request #6 from Alymosul/addSupportToJsonData
Add support to json data
2 parents cc2f594 + c19eeba commit 504a7ec

File tree

3 files changed

+57
-4
lines changed

3 files changed

+57
-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: 42 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,32 @@ 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+
} elseif (is_string($data)) {
147+
@json_decode($data);
148+
149+
if (json_last_error() !== JSON_ERROR_NONE) {
150+
throw new CouldNotCreateMessage('Invalid json format passed to the setJsonData().');
151+
}
152+
}
153+
154+
$this->jsonData = $data;
155+
156+
return $this;
157+
}
158+
122159
/**
123160
* Get an array representation of the message.
124161
*
@@ -127,10 +164,11 @@ public function setTtl(int $ttl)
127164
public function toArray()
128165
{
129166
return [
130-
'body' => $this->body,
131-
'sound' => $this->sound,
132-
'badge' => $this->badge,
133-
'ttl' => $this->ttl,
167+
'body' => $this->body,
168+
'sound' => $this->sound,
169+
'badge' => $this->badge,
170+
'ttl' => $this->ttl,
171+
'data' => $this->jsonData,
134172
];
135173
}
136174
}

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(), 'data'));
100+
}
93101
}

0 commit comments

Comments
 (0)