Completed
Push — master ( 80f1a6...8c34ac )
by Dominik
03:50
created

AzineNotifierServiceTest::getMockSetup()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 2 Features 1
Metric Value
c 7
b 2
f 1
dl 0
loc 25
rs 8.8571
cc 1
eloc 21
nc 1
nop 0
1
<?php
2
namespace Azine\EmailBundle\Tests\Services;
3
4
use Azine\EmailBundle\Services\ExampleNotifierService;
5
use Azine\EmailBundle\Entity\Notification;
6
use Azine\EmailBundle\Services\TemplateProviderInterface;
7
use Azine\EmailBundle\Services\AzineNotifierService;
8
use Doctrine\ORM\EntityManager;
9
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
10
use Monolog\Logger;
11
use Azine\EmailBundle\Services\TemplateTwigSwiftMailerInterface;
12
use Azine\EmailBundle\Tests\AzineQueryMock;
13
use Azine\EmailBundle\Entity\RecipientInterface;
14
use Azine\EmailBundle\DependencyInjection\AzineEmailExtension;
15
use Azine\EmailBundle\Services\AzineTemplateProvider;
16
17
class AzineNotifierServiceTest extends \PHPUnit_Framework_TestCase
18
{
19
    private function getMockSetup()
20
    {
21
        $mocks = array();
22
        $mocks['mailer'] = $this->getMockBuilder("Azine\EmailBundle\Services\TemplateTwigSwiftMailerInterface")->disableOriginalConstructor()->getMock();
23
        $mocks['twig'] = $this->getMockBuilder("\Twig_Environment")->disableOriginalConstructor()->getMock();
24
        $mocks['logger'] = $this->getMockBuilder("Monolog\Logger")->disableOriginalConstructor()->getMock();
25
        $mocks['router'] = $this->getMockBuilder("Symfony\Component\Routing\Generator\UrlGeneratorInterface")->disableOriginalConstructor()->getMock();
26
        $mocks['entityManager'] = $this->getMockBuilder("Doctrine\ORM\EntityManager")->disableOriginalConstructor()->getMock();
27
        $mocks['notificationRepository'] = $this->getMockBuilder("Azine\EmailBundle\Entity\Repositories\NotificationRepository")->disableOriginalConstructor()->getMock();
28
        $mocks['managerRegistry'] = $this->getMockBuilder("Doctrine\Common\Persistence\ManagerRegistry")->disableOriginalConstructor()->getMock();
29
        $mocks['managerRegistry']->expects($this->any())->method("getManager")->will($this->returnValue($mocks['entityManager']));
30
        $mocks['managerRegistry']->expects($this->any())->method("getRepository")->will($this->returnValue($mocks['notificationRepository']));
31
        $mocks['templateProvider'] = $this->getMockBuilder("Azine\EmailBundle\Services\TemplateProviderInterface")->disableOriginalConstructor()->getMock();
32
        $mocks['recipientProvider'] = $this->getMockBuilder("Azine\EmailBundle\Services\RecipientProviderInterface")->disableOriginalConstructor()->getMock();
33
        $mocks['translator'] = $this->getMockBuilder("Symfony\Bundle\FrameworkBundle\Translation\Translator")->disableOriginalConstructor()->getMock();
34
        $mocks['parameters'] = array(
35
                                AzineEmailExtension::NEWSLETTER."_".AzineEmailExtension::NEWSLETTER_INTERVAL => '7',
36
                                AzineEmailExtension::NEWSLETTER."_".AzineEmailExtension::NEWSLETTER_SEND_TIME => '09:00',
37
                                AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::NEWSLETTER_TEMPLATE =>	AzineTemplateProvider::NEWSLETTER_TEMPLATE,
38
                                AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::NOTIFICATIONS_TEMPLATE =>	AzineTemplateProvider::NOTIFICATIONS_TEMPLATE,
39
                                AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::CONTENT_ITEM_TEMPLATE =>	AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TEMPLATE
40
                                    );
41
42
        return $mocks;
43
    }
44
45
    public function testAddNotification()
46
    {
47
        $mocks = $this->getMockSetup();
48
        $mocks['entityManager']->expects($this->once())->method('persist');
49
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
50
51
        $n = $notifier->addNotification("12", "title", "content", "template", array("templateVars"), 1, false);
52
53
        $this->assertEquals("12", $n->getRecipientId());
54
        $this->assertEquals("title", $n->getTitle());
55
        $this->assertEquals("template", $n->getTemplate());
56
        $this->assertEquals(array("templateVars"), $n->getVariables());
57
    }
58
59
    public function testAddNotificationMessage()
60
    {
61
        $goToUrl = "http://azine.email/this/is/a/url";
62
        $templateVars = array('logo_png' => '/some/directory/logo.png', 'mainColor' => 'green');
63
        $mocks = $this->getMockSetup();
64
        $mocks['entityManager']->expects($this->once())->method('persist');
65
        $mocks['templateProvider']->expects($this->once())->method("addTemplateVariablesFor")->with(AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TEMPLATE, array('goToUrl' => $goToUrl))->will($this->returnValue(array_merge(array('goToUrl' => $goToUrl), $templateVars)));
66
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
67
68
        $notifier->addNotificationMessage("12", "some title", "some content with \nline breaks.", $goToUrl);
69
70
        $mocks = $this->getMockSetup();
71
        $mocks['entityManager']->expects($this->once())->method('persist');
72
        $mocks['templateProvider']->expects($this->once())->method("addTemplateVariablesFor")->with(AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TEMPLATE, array())->will($this->returnValue($templateVars));
73
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
74
75
        $notifier->addNotificationMessage("12", "some title", "some content with \nline breaks.");
76
    }
77
78
    public function testSendNewsletter()
79
    {
80
        $failedAddresses = array();
81
        $recipientIds = array(11,12,13,14);
82
        $mocks = $this->getMockSetup();
83
        $this->mockRecipients($mocks['recipientProvider'], $recipientIds);
84
        $mocks['recipientProvider']->expects($this->once())->method("getNewsletterRecipientIDs")->will($this->returnValue($recipientIds));
85
        $mocks['mailer']->expects($this->exactly(sizeof($recipientIds)))->method("sendSingleEmail")->will($this->returnCallback(array($this, 'sendSingleEmailCallBack')));
86
87
        $mocks['mailer']->expects($this->exactly(sizeof($recipientIds)))->method("sendSingleEmail");
88
        $mocks['logger']->expects($this->never())->method("warning");
89
        $mocks['logger']->expects($this->once())->method("error"); // see sendSingleEmailCallBack, one mail-address fails
90
91
        $notifier = new ExampleNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
92
        $sentMails = $notifier->sendNewsletter($failedAddresses);
93
        $this->assertEquals(1, sizeof($failedAddresses));
94
        $this->assertEquals(sizeof($recipientIds)-1, $sentMails);
95
    }
96
97
    public function sendSingleEmailCallBack($email, $displayName, $params, $wrapperTemplate, $locale)
98
    {
99
        if ($email == "[email protected]") {
100
            return false;
101
        }
102
103
        return true;
104
    }
105
106
    public function testSendNewsletter_NoContent()
107
    {
108
        $failedAddresses = array();
109
        $recipientIds = array(11,12,13,14);
110
        $mocks = $this->getMockSetup();
111
        $this->mockRecipients($mocks['recipientProvider'], $recipientIds);
112
        $mocks['recipientProvider']->expects($this->once())->method("getNewsletterRecipientIDs")->will($this->returnValue($recipientIds));
113
114
        $mocks['mailer']->expects($this->never())->method("sendSingleEmail");
115
        $mocks['logger']->expects($this->exactly(4))->method("warning");
116
        $mocks['logger']->expects($this->never())->method("error");
117
118
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
119
        $sentMails = $notifier->sendNewsletter($failedAddresses);
120
        $this->assertEquals(4, sizeof($failedAddresses), "Email-addresses failed unexpectedly:".print_r($failedAddresses,true));
121
        $this->assertEquals(0, $sentMails, "Not the expected number of sent emails.");
122
    }
123
124
    public function testSendNotificationsAzineNotifierService()
125
    {
126
        $failedAddresses = array();
127
        $recipientIds = array(11,12,13,14);
128
        $mocks = $this->getMockSetup();
129
        $this->mockRecipients($mocks['recipientProvider'], $recipientIds);
130
        $mocks['mailer']->expects($this->exactly(sizeof($recipientIds)))->method("sendSingleEmail")->will($this->returnCallback(array($this, 'sendSingleEmailCallBack')));
131
132
        $notification = new Notification();
133
        $notification->setContent("bla bla");
134
        $notification->setCreated(new \DateTime());
135
        $notification->setImportance(0);
136
        $notification->setTemplate(AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TEMPLATE);
137
        $notification->setVariables(array('blabla' => 'blablaValue'));
138
        $notification->setTitle("a title");
139
140
        $mocks['notificationRepository']->expects($this->once())->method('getNotificationRecipientIds')->will($this->returnValue($recipientIds));
141
        $mocks['notificationRepository']->expects($this->exactly(4))->method('getNotificationsToSend')->will($this->returnValue(array($notification)));
142
        $mocks['notificationRepository']->expects($this->never())->method('getNotificationsToSendImmediately');
143
        $mocks['notificationRepository']->expects($this->never())->method('markAllNotificationsAsSentFarInThePast');
144
        $mocks['notificationRepository']->expects($this->exactly(4))->method('getLastNotificationDate')->will($this->returnValue(new \DateTime("@0")));
145
146
        $mocks['logger']->expects($this->never())->method("warning");
147
        $mocks['logger']->expects($this->once())->method("error"); // see sendSingleEmailCallBack, one mail-address fails
148
149
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
150
        $sentMails = $notifier->sendNotifications($failedAddresses);
151
        $this->assertEquals(1, sizeof($failedAddresses), "One failed address was expected.");
152
        $this->assertEquals(sizeof($recipientIds)-sizeof($failedAddresses), $sentMails, "Not the right number of emails has been sent successfully. Expected ".sizeof($recipientIds)-sizeof($failedAddresses));
153
154
    }
155
156
    public function testSendNotificationsAzineNotifierService_NoNotifications()
157
    {
158
        $failedAddresses = array();
159
        $recipientIds = array(11,12,13,14);
160
        $mocks = $this->getMockSetup();
161
        $this->mockRecipients($mocks['recipientProvider'], $recipientIds);
162
        $mocks['mailer']->expects($this->never())->method("sendSingleEmail")->will($this->returnCallback(array($this, 'sendSingleEmailCallBack')));
163
164
        $mocks['notificationRepository']->expects($this->once())->method('getNotificationRecipientIds')->will($this->returnValue($recipientIds));
165
        $mocks['notificationRepository']->expects($this->exactly(4))->method('getNotificationsToSend')->will($this->returnValue(array()));
166
        $mocks['notificationRepository']->expects($this->never())->method('getNotificationsToSendImmediately');
167
        $mocks['notificationRepository']->expects($this->never())->method('markAllNotificationsAsSentFarInThePast');
168
        $mocks['notificationRepository']->expects($this->exactly(4))->method('getLastNotificationDate')->will($this->returnValue(new \DateTime("@0")));
169
170
        $mocks['logger']->expects($this->never())->method("warning");
171
        $mocks['logger']->expects($this->never())->method("error"); // see sendSingleEmailCallBack, one mail-address fails
172
173
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
174
        $sentMails = $notifier->sendNotifications($failedAddresses);
175
        $this->assertEquals(0, sizeof($failedAddresses), "Email-addresses failed unexpectedly:".print_r($failedAddresses,true));
176
        $this->assertEquals(4, $sentMails, "Not the expected number of sent emails.");
177
178
    }
179
    public function testSendNotificationsExampleNotifier()
180
    {
181
        $failedAddresses = array();
182
        $recipientIds = array(11,12,13,14);
183
        $mocks = $this->getMockSetup();
184
        $this->mockRecipients($mocks['recipientProvider'], $recipientIds);
185
        $mocks['mailer']->expects($this->exactly(sizeof($recipientIds)))->method("sendSingleEmail")->will($this->returnCallback(array($this, 'sendSingleEmailCallBack')));
186
187
        $notification = new Notification();
188
        $notification->setContent("bla bla");
189
        $notification->setCreated(new \DateTime());
190
        $notification->setImportance(0);
191
        $notification->setTemplate(AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TEMPLATE);
192
        $notification->setVariables(array('blabla' => 'blablaValue'));
193
        $notification->setTitle("a title");
194
195
        $mocks['notificationRepository']->expects($this->once())->method('getNotificationRecipientIds')->will($this->returnValue($recipientIds));
196
        $mocks['notificationRepository']->expects($this->exactly(4))->method('getNotificationsToSend')->will($this->returnValue(array($notification)));
197
        $mocks['notificationRepository']->expects($this->never())->method('getNotificationsToSendImmediately');
198
        $mocks['notificationRepository']->expects($this->never())->method('markAllNotificationsAsSentFarInThePast');
199
        $mocks['notificationRepository']->expects($this->exactly(4))->method('getLastNotificationDate')->will($this->returnValue(new \DateTime("@0")));
200
201
        $mocks['mailer']->expects($this->exactly(sizeof($recipientIds)))->method("sendSingleEmail");
202
        $mocks['logger']->expects($this->never())->method("warning");
203
        $mocks['logger']->expects($this->once())->method("error"); // see sendSingleEmailCallBack, one mail-address fails
204
205
        $notifier = new ExampleNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
206
        $sentMails = $notifier->sendNotifications($failedAddresses);
207
        $this->assertEquals(1, sizeof($failedAddresses));
208
        $this->assertEquals(sizeof($recipientIds)-1, $sentMails);
209
210
    }
211
212
    private function mockRecipients(\PHPUnit_Framework_MockObject_MockObject $mock, array $ids)
213
    {
214
        $notificationType = 0;
215
        $notificationTypes = array(RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY, RecipientInterface::NOTIFICATION_MODE_HOURLY, RecipientInterface::NOTIFICATION_MODE_DAYLY);
216
        $valueMap = array();
217
        foreach ($ids as $id) {
218
            $recipientMock = $this->getMockBuilder("Azine\EmailBundle\Entity\RecipientInterface")->disableOriginalConstructor()->getMock();
219
            $recipientMock->expects($this->any())->method("getEmail")->will($this->returnValue($id."[email protected]"));
220
            $recipientMock->expects($this->any())->method("getDisplayName")->will($this->returnValue("DisplayName of $id"));
221
            $recipientMock->expects($this->any())->method("getPreferredLocale")->will($this->returnValue("en"));
222
            $recipientMock->expects($this->any())->method("getNotificationMode")->will($this->returnValue($notificationTypes[$notificationType%sizeof($notificationTypes)]));
223
            $notificationType++;
224
            $valueMap[] = array($id,$recipientMock);
225
        }
226
227
        $mock->expects($this->exactly(sizeof($ids)))->method("getRecipient")->will($this->returnValueMap($valueMap));
228
    }
229
230
    public function testProtectedMethods()
231
    {
232
        // create service-instance
233
        $mocks = $this->getMockSetup();
234
235
        $recipientIds = array(11,12,13,14);
236
        $mocks['recipientProvider']->expects($this->once())->method("getNewsletterRecipientIDs")->will($this->returnValue($recipientIds));
237
238
        $notifier = new AzineNotifierService($mocks['mailer'], $mocks['twig'], $mocks['logger'], $mocks['router'], $mocks['managerRegistry'], $mocks['templateProvider'], $mocks['recipientProvider'], $mocks['translator'], $mocks['parameters']);
239
240
        // access the protected method and execute it
241
        $returnValue = self::getMethod('getDateTimeOfLastNewsletter')->invokeArgs($notifier, array());
242
        $this->assertInstanceOf("DateTime", $returnValue);
243
        $lastDate = new \DateTime("7 days ago");
244
        $lastDate->setTime(9, 0);
245
        $this->assertEquals($lastDate, $returnValue);
246
247
        $returnValue = self::getMethod('getDateTimeOfNextNewsletter')->invokeArgs($notifier, array());
248
        $this->assertInstanceOf("DateTime", $returnValue);
249
        $nextDate = new \DateTime("7 days");
250
        $nextDate->setTime(9, 0);
251
        $this->assertEquals($nextDate, $returnValue);
252
253
        $returnValue = self::getMethod('getHourInterval')->invokeArgs($notifier, array());
254
        $this->assertEquals((60*60 - 3*60), $returnValue);
255
256
        $returnValue = self::getMethod('getGeneralVarsForNewsletter')->invokeArgs($notifier, array());
257
        $this->assertEquals(sizeof($recipientIds), $returnValue['recipientCount']);
258
259
        $recipientMock = $this->getMockBuilder("Azine\EmailBundle\Entity\RecipientInterface")->disableOriginalConstructor()->getMock();
260
        $recipientMock->expects($this->any())->method("getId")->will($this->returnValue(11));
261
262
        $returnValue = self::getMethod('markAllNotificationsAsSentFarInThePast')->invokeArgs($notifier, array($recipientMock));
0 ignored issues
show
Unused Code introduced by
$returnValue is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
263
264
    }
265
266
    /**
267
     * @param string $name
268
     */
269 View Code Duplication
    private static function getMethod($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
270
    {
271
        $class = new \ReflectionClass("Azine\EmailBundle\Services\AzineNotifierService");
272
        $method = $class->getMethod($name);
273
        $method->setAccessible(true);
274
275
        return $method;
276
    }
277
278
}
279