|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace IrishDan\NotificationBundle\Formatter; |
|
4
|
|
|
|
|
5
|
|
|
use IrishDan\NotificationBundle\Message\Message; |
|
6
|
|
|
use IrishDan\NotificationBundle\Notification\NotificationInterface; |
|
7
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
|
8
|
|
|
|
|
9
|
|
|
abstract class BaseFormatter |
|
10
|
|
|
{ |
|
11
|
|
|
protected $twig; |
|
12
|
|
|
protected $eventDispatcher; |
|
13
|
|
|
|
|
14
|
|
|
public function setTemplating(\Twig_Environment $twig) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->twig = $twig; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function setDispatcher(EventDispatcherInterface $eventDispatcher) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->eventDispatcher = $eventDispatcher; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
protected function renderTwigTemplate($data, $user, $template) |
|
25
|
|
|
{ |
|
26
|
|
|
return $this->twig->render( |
|
27
|
|
|
$template, |
|
28
|
|
|
[ |
|
29
|
|
|
'data' => $data, |
|
30
|
|
|
'user' => $user, |
|
31
|
|
|
] |
|
32
|
|
|
); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function format(NotificationInterface $notification) |
|
36
|
|
|
{ |
|
37
|
|
|
if (!empty($this->twig) && $notification->getTemplate()) { |
|
38
|
|
|
$data = $notification->getDataArray(); |
|
39
|
|
|
$data['body'] = $this->renderTwigTemplate( |
|
40
|
|
|
$data, |
|
41
|
|
|
$notification->getNotifiable(), |
|
42
|
|
|
$notification->getTemplate() |
|
43
|
|
|
); |
|
44
|
|
|
|
|
45
|
|
|
$notification->setDataArray($data); |
|
|
|
|
|
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
static protected function createMessage($dispatchData, $messageData, $channel = 'default') |
|
|
|
|
|
|
50
|
|
|
{ |
|
51
|
|
|
$message = new Message(); |
|
52
|
|
|
|
|
53
|
|
|
$message->setChannel($channel); |
|
54
|
|
|
$message->setDispatchData($dispatchData); |
|
55
|
|
|
$message->setMessageData($messageData); |
|
56
|
|
|
|
|
57
|
|
|
return $message; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
static protected function createMessagaData(array $notificationData) |
|
|
|
|
|
|
61
|
|
|
{ |
|
62
|
|
|
// Build the message data array. |
|
63
|
|
|
$messageData = []; |
|
64
|
|
|
$messageData['body'] = empty($notificationData['body']) ? '' : $notificationData['body']; |
|
65
|
|
|
$messageData['title'] = empty($notificationData['title']) ? '' : $notificationData['title']; |
|
66
|
|
|
|
|
67
|
|
|
return $messageData; |
|
68
|
|
|
} |
|
69
|
|
|
} |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: