1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace IrishDan\NotificationBundle\Formatter; |
4
|
|
|
|
5
|
|
|
use IrishDan\NotificationBundle\Exception\MessageFormatException; |
6
|
|
|
use IrishDan\NotificationBundle\Message\Message; |
7
|
|
|
use IrishDan\NotificationBundle\Notification\NotificationInterface; |
8
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
9
|
|
|
|
10
|
|
|
abstract class BaseFormatter |
11
|
|
|
{ |
12
|
|
|
protected $twig; |
13
|
|
|
protected $eventDispatcher; |
14
|
|
|
|
15
|
|
|
public function setTemplating(\Twig_Environment $twig) |
16
|
|
|
{ |
17
|
|
|
$this->twig = $twig; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function setDispatcher(EventDispatcherInterface $eventDispatcher) |
21
|
|
|
{ |
22
|
|
|
$this->eventDispatcher = $eventDispatcher; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
protected function renderTwigTemplate($data, $user, $template) |
26
|
|
|
{ |
27
|
|
|
return $this->twig->render( |
28
|
|
|
$template, |
29
|
|
|
[ |
30
|
|
|
'data' => $data, |
31
|
|
|
'user' => $user, |
32
|
|
|
] |
33
|
|
|
); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function format(NotificationInterface $notification) |
37
|
|
|
{ |
38
|
|
|
if (!empty($this->twig) && $notification->getTemplate()) { |
39
|
|
|
$data = $notification->getDataArray(); |
40
|
|
|
$data['body'] = $this->renderTwigTemplate( |
41
|
|
|
$data, |
42
|
|
|
$notification->getNotifiable(), |
43
|
|
|
$notification->getTemplate() |
44
|
|
|
); |
45
|
|
|
|
46
|
|
|
$notification->setDataArray($data); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected static function createMessage($dispatchData, $messageData, $channel = 'default') |
51
|
|
|
{ |
52
|
|
|
$message = new Message(); |
53
|
|
|
|
54
|
|
|
$message->setChannel($channel); |
55
|
|
|
$message->setDispatchData($dispatchData); |
56
|
|
|
$message->setMessageData($messageData); |
57
|
|
|
|
58
|
|
|
return $message; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
protected static function createMessagaData(array $notificationData) |
62
|
|
|
{ |
63
|
|
|
// Build the message data array. |
64
|
|
|
$messageData = []; |
65
|
|
|
$messageData['body'] = empty($notificationData['body']) ? '' : $notificationData['body']; |
66
|
|
|
$messageData['title'] = empty($notificationData['title']) ? '' : $notificationData['title']; |
67
|
|
|
|
68
|
|
|
return $messageData; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected static function createFormatterException($shouldImplement, $type) |
72
|
|
|
{ |
73
|
|
|
$message = sprintf('Notifiable must implement %s interface in order to format as a %s message', |
74
|
|
|
$shouldImplement, $type); |
75
|
|
|
throw new MessageFormatException( |
76
|
|
|
$message |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
} |