Completed
Push — master ( 01eb7b...2ee407 )
by Alejandro
09:40 queued 07:02
created

testFileAttachments()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 28
rs 8.8571
cc 1
eloc 19
nc 1
nop 0
1
<?php
2
namespace AcMailerTest\Service;
3
4
use AcMailer\Event\MailEvent;
5
use AcMailer\Options\MailOptions;
6
use AcMailer\Service\Factory\MailServiceAbstractFactory;
7
use AcMailer\Service\Factory\MailServiceFactory;
8
use AcMailerTest\Event\MailListenerMock;
9
use AcMailerTest\ServiceManager\ServiceManagerMock;
10
use Zend\EventManager\EventManagerAwareInterface;
11
use Zend\Mail\Transport\File;
12
use Zend\Mail\Transport\Sendmail;
13
use Zend\Mail\Transport\Smtp;
14
use Zend\Mime\Message;
15
use Zend\ServiceManager\ServiceLocatorInterface;
16
use Zend\Stdlib\ArrayUtils;
17
use Zend\View\Renderer\PhpRenderer;
18
use Zend\View\Resolver\TemplatePathStack;
19
use PHPUnit_Framework_TestCase as TestCase;
20
21
/**
22
 * Class MailServiceFactoryTest
23
 * @author Alejandro Celaya Alastrué
24
 * @link http://www.alejandrocelaya.com
25
 */
26
class MailServiceAbstractFactoryTest extends TestCase
27
{
28
    /**
29
     * @var MailServiceAbstractFactory
30
     */
31
    private $mailServiceFactory;
32
    /**
33
     * @var ServiceLocatorInterface
34
     */
35
    private $serviceLocator;
36
37
    public function setUp()
38
    {
39
        $this->mailServiceFactory = new MailServiceAbstractFactory();
40
    }
41
42
    public function testMessageData()
43
    {
44
        $options = [
45
            'message_options' => [
46
                'from'          => '[email protected]',
47
                'from_name'     => 'Alejandro Celaya',
48
                'reply_to'      => '[email protected]',
49
                'reply_to_name' => 'Alejandro Celaya',
50
                'to'            => ['[email protected]', '[email protected]'],
51
                'cc'            => ['[email protected]'],
52
                'bcc'           => ['[email protected]'],
53
                'subject'       => 'The subject',
54
                'body'          => ['content' => 'The body'],
55
            ]
56
        ];
57
        $this->initServiceLocator($options);
58
        $mailService = $this->mailServiceFactory->__invoke(
59
            $this->serviceLocator,
60
            'acmailer.mailservice.default'
61
        );
62
63
        $this->assertInstanceOf('AcMailer\Service\MailService', $mailService);
64
        $this->assertEquals(
65
            $options['message_options']['from_name'],
66
            $mailService->getMessage()->getFrom()->get($options['message_options']['from'])->getName()
67
        );
68
        $this->assertEquals(
69
            $options['message_options']['reply_to_name'],
70
            $mailService->getMessage()->getReplyTo()->get($options['message_options']['reply_to'])->getName()
71
        );
72
        $toArray = array_keys(ArrayUtils::iteratorToArray($mailService->getMessage()->getTo()));
73
        $ccArray = array_keys(ArrayUtils::iteratorToArray($mailService->getMessage()->getCc()));
74
        $bccArray = array_keys(ArrayUtils::iteratorToArray($mailService->getMessage()->getBcc()));
75
        $this->assertEquals($options['message_options']['to'], $toArray);
76
        $this->assertEquals($options['message_options']['cc'], $ccArray);
77
        $this->assertEquals($options['message_options']['bcc'], $bccArray);
78
        $this->assertEquals($options['message_options']['subject'], $mailService->getMessage()->getSubject());
79
        $this->assertInstanceOf(Message::class, $mailService->getMessage()->getBody());
80
    }
81
82
    public function testSmtpAdapter()
83
    {
84
        $options = [
85
            'mail_adapter' => 'Zend\Mail\Transport\Smtp',
86
            'smtp_options' => [
87
                'host'  => 'the.host',
88
                'port'  => 465,
89
                'connection_config' => [
90
                    'username'  => 'alejandro',
91
                    'password'  => '1234',
92
                    'ssl'       => 'ssl',
93
                ]
94
            ]
95
        ];
96
        $this->initServiceLocator($options);
97
        $mailService = $this->mailServiceFactory->__invoke(
98
            $this->serviceLocator,
99
            'acmailer.mailservice.default'
100
        );
101
102
        /* @var Smtp $transport */
103
        $transport = $mailService->getTransport();
104
        $this->assertInstanceOf($options['mail_adapter'], $transport);
105
        $connConfig = $transport->getOptions()->getConnectionConfig();
106
        $this->assertEquals($options['smtp_options']['connection_config']['username'], $connConfig['username']);
107
        $this->assertEquals($options['smtp_options']['connection_config']['password'], $connConfig['password']);
108
        $this->assertEquals($options['smtp_options']['connection_config']['ssl'], $connConfig['ssl']);
109
        $this->assertEquals($options['smtp_options']['host'], $transport->getOptions()->getHost());
110
        $this->assertEquals($options['smtp_options']['port'], $transport->getOptions()->getPort());
111
    }
112
113
    public function testFileAdapter()
114
    {
115
        $options = [
116
            'mail_adapter'  => 'file',
117
            'file_options' => [
118
                'path'     => __DIR__,
119
                'callback' => function ($transport) {
120
                    return get_class($transport);
121
                }
122
            ]
123
        ];
124
        $this->initServiceLocator($options);
125
        $mailService = $this->mailServiceFactory->__invoke(
126
            $this->serviceLocator,
127
            'acmailer.mailservice.default'
128
        );
129
130
        /* @var File $transport */
131
        $transport = $mailService->getTransport();
132
        $this->assertInstanceOf('Zend\Mail\Transport\File', $transport);
133
        $this->assertEquals($options['file_options']['path'], $transport->getOptions()->getPath());
134
        $this->assertEquals($options['file_options']['callback'], $transport->getOptions()->getCallback());
135
    }
136
137 View Code Duplication
    public function testAdapterAsService()
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...
138
    {
139
        $this->initServiceLocator([
140
            'mail_adapter' => 'my_transport_service'
141
        ]);
142
        $transport = new Sendmail();
143
        $this->serviceLocator->set('my_transport_service', $transport);
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
144
        $mailService = $this->mailServiceFactory->__invoke(
145
            $this->serviceLocator,
146
            'acmailer.mailservice.default'
147
        );
148
        $this->assertSame($transport, $mailService->getTransport());
149
    }
150
151
    /**
152
     * @expectedException \AcMailer\Exception\InvalidArgumentException
153
     */
154
    public function testAdapterAsInvalidService()
155
    {
156
        $this->initServiceLocator([
157
            'mail_adapter' => 'my_transport_service'
158
        ]);
159
        $this->mailServiceFactory->__invoke(
160
            $this->serviceLocator,
161
            'acmailer.mailservice.default'
162
        );
163
    }
164
165
    /**
166
     * @expectedException \AcMailer\Exception\InvalidArgumentException
167
     */
168
    public function testAdapterAsAserviceNotReturningTransport()
169
    {
170
        $this->initServiceLocator([
171
            'mail_adapter' => 'my_transport_service'
172
        ]);
173
        $this->serviceLocator->set('my_transport_service', new \stdClass());
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
174
        $this->mailServiceFactory->__invoke(
175
            $this->serviceLocator,
176
            'acmailer.mailservice.default'
177
        );
178
    }
179
180 View Code Duplication
    public function testAdapterAsInstance()
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...
181
    {
182
        $expected = new Sendmail();
183
        $this->initServiceLocator([
184
            'mail_adapter' => $expected
185
        ]);
186
        $mailService = $this->mailServiceFactory->__invoke(
187
            $this->serviceLocator,
188
            'acmailer.mailservice.default'
189
        );
190
        $this->assertSame($expected, $mailService->getTransport());
191
    }
192
193
    public function testViewRendererService()
194
    {
195
        $this->initServiceLocator();
196
        // Create the service with default configuration
197
        $mailService = $this->mailServiceFactory->__invoke(
198
            $this->serviceLocator,
199
            'acmailer.mailservice.default'
200
        );
201
        /** @var PhpRenderer $renderer */
202
        $renderer = $mailService->getRenderer();
203
        $this->assertInstanceOf('Zend\View\Renderer\PhpRenderer', $renderer);
204
        $this->assertInstanceOf('Zend\View\Resolver\TemplatePathStack', $renderer->resolver());
205
206
        // Set a template_map and unset the template_path_stack
207
        $config = $this->serviceLocator->get('Config');
208
        unset($config['view_manager']['template_path_stack']);
209
        $config['view_manager']['template_map'] = [];
210
        $this->serviceLocator->set('Config', $config);
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
211
        $mailService = $this->mailServiceFactory->__invoke(
212
            $this->serviceLocator,
213
            'acmailer.mailservice.default'
214
        );
215
        /** @var PhpRenderer $renderer */
216
        $renderer = $mailService->getRenderer();
217
        $this->assertInstanceOf('Zend\View\Renderer\PhpRenderer', $renderer);
218
        $this->assertInstanceOf('Zend\View\Resolver\TemplateMapResolver', $renderer->resolver());
219
220
        // Set both a template_map and a template_path_stack
221
        $this->initServiceLocator();
222
        $config = $this->serviceLocator->get('Config');
223
        $config['view_manager']['template_map'] = [];
224
        $this->serviceLocator->set('Config', $config);
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
225
        $mailService = $this->mailServiceFactory->__invoke(
226
            $this->serviceLocator,
227
            'acmailer.mailservice.default'
228
        );
229
        /** @var PhpRenderer $renderer */
230
        $renderer = $mailService->getRenderer();
231
        $this->assertInstanceOf('Zend\View\Renderer\PhpRenderer', $renderer);
232
        $this->assertInstanceOf('Zend\View\Resolver\AggregateResolver', $renderer->resolver());
233
234
        // Set a viewrenderer service and see if it is used
235
        $renderer = new PhpRenderer();
236
        $this->serviceLocator->set('mailviewrenderer', $renderer);
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
237
        $mailService = $this->mailServiceFactory->__invoke(
238
            $this->serviceLocator,
239
            'acmailer.mailservice.default'
240
        );
241
        $this->assertSame($renderer, $mailService->getRenderer());
242
    }
243
244
    public function testTemplateBody()
245
    {
246
        $options = [
247
            'message_options' => [
248
                'body' => [
249
                    'content' => 'This body is not going to be used',
250
                    'use_template'  => true,
251
                    'template' => [
252
                        'path'          => 'ac-mailer/mail-templates/layout',
253
                        'children'      => [
254
                            'content'   => [
255
                                'path'   => 'ac-mailer/mail-templates/mail',
256
                            ]
257
                        ]
258
                    ],
259
                ]
260
            ]
261
        ];
262
        $this->initServiceLocator($options);
263
264
        $resolver = new TemplatePathStack();
265
        $resolver->addPath(__DIR__ . '/../../view');
266
        $renderer = new PhpRenderer();
267
        $renderer->setResolver($resolver);
268
        $this->serviceLocator->set('mailviewrenderer', $renderer);
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
269
        $mailService = $this->mailServiceFactory->__invoke(
270
            $this->serviceLocator,
271
            'acmailer.mailservice.default'
272
        );
273
274
        $this->assertNotEquals($options ['message_options']['body']['content'], $mailService->getMessage()->getBody());
275
        $this->assertInstanceOf('Zend\Mime\Message', $mailService->getMessage()->getBody());
276
    }
277
278
    public function testWithDefaultLayout()
279
    {
280
        $options = [
281
            'message_options' => [
282
                'body' => [
283
                    'use_template'  => true,
284
                    'template' => [
285
                        'path'          => 'ac-mailer/mail-templates/mail',
286
                        'default_layout' => [
287
                            'path' => 'ac-mailer/mail-templates/layout',
288
                        ]
289
                    ],
290
                ]
291
            ]
292
        ];
293
        $this->initServiceLocator($options);
294
295
        $resolver = new TemplatePathStack();
296
        $resolver->addPath(__DIR__ . '/../../view');
297
        $renderer = new PhpRenderer();
298
        $renderer->setResolver($resolver);
299
        $this->serviceLocator->set('mailviewrenderer', $renderer);
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
300
        $mailService = $this->mailServiceFactory->__invoke(
301
            $this->serviceLocator,
302
            'acmailer.mailservice.default'
303
        );
304
        $this->assertInstanceOf('Zend\Mime\Message', $mailService->getMessage()->getBody());
305
    }
306
307
    public function testFileAttachments()
308
    {
309
        $cwd = getcwd();
310
        chdir(dirname(__DIR__));
311
        $options = [
312
            'message_options' => [
313
                'attachments' => [
314
                    'files' => [
315
                        'attachments/file1',
316
                        'attachments/file2',
317
                    ],
318
                    'dir' => [
319
                        'iterate'   => true,
320
                        'path'      => 'attachments/dir',
321
                        'recursive' => true,
322
                    ],
323
                ],
324
            ]
325
        ];
326
        $this->initServiceLocator($options);
327
        $mailService = $this->mailServiceFactory->__invoke(
328
            $this->serviceLocator,
329
            'acmailer.mailservice.default'
330
        );
331
332
        $this->assertCount(4, $mailService->getAttachments());
333
        chdir($cwd);
334
    }
335
336
    public function testListeners()
337
    {
338
        $options = [
339
            'mail_listeners' => [
340
                new MailListenerMock(),
341
                'mail_listener_service',
342
                'AcMailerTest\Event\MailListenerMock'
343
            ]
344
        ];
345
        $this->initServiceLocator($options);
346
        $this->serviceLocator->set('mail_listener_service', new MailListenerMock());
0 ignored issues
show
Bug introduced by
The method set() does not seem to exist on object<Zend\ServiceManag...erviceLocatorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
347
348
        /** @var EventManagerAwareInterface $mailService */
349
        $mailService = $this->mailServiceFactory->__invoke(
350
            $this->serviceLocator,
351
            'acmailer.mailservice.default'
352
        );
353
354
        // Make getListenersByEventName method public
355
        $em = $mailService->getEventManager();
356
        $refObject = new \ReflectionObject($em);
357
        $method = $refObject->getMethod('getListenersByEventName');
358
        $method->setAccessible(true);
359
360
        $this->assertCount(3, $method->invoke($em, MailEvent::EVENT_MAIL_PRE_SEND));
361
    }
362
363
    /**
364
     * @expectedException \AcMailer\Exception\InvalidArgumentException
365
     */
366
    public function testInvalidListenersThrowException()
367
    {
368
        $options = [
369
            'mail_listeners' => [
370
                new \stdClass(),
371
                'invalid_service',
372
                '\Nonsens\Foo'
373
            ]
374
        ];
375
        $this->initServiceLocator($options);
376
        $this->mailServiceFactory->__invoke(
377
            $this->serviceLocator,
378
            'acmailer.mailservice.default'
379
        );
380
    }
381
382
    private function initServiceLocator(array $mailOptions = [])
383
    {
384
        $this->serviceLocator = new ServiceManagerMock([
0 ignored issues
show
Documentation Bug introduced by
It seems like new \AcMailerTest\Servic...ig/module.config.php')) of type object<AcMailerTest\Serv...ger\ServiceManagerMock> is incompatible with the declared type object<Zend\ServiceManag...erviceLocatorInterface> of property $serviceLocator.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
385
            'acmailer.mailoptions.default' => new MailOptions($mailOptions),
386
            'Config' => include __DIR__ . '/../../config/module.config.php'
387
        ]);
388
    }
389
}
390