Passed
Push — master ( 134f11...d02ad4 )
by Alexander
08:37
created

MessageTest::testAttachSigners()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Mailer\SwiftMailer\Tests;
4
5
use Yiisoft\Mailer\SwiftMailer\Message;
6
7
class MessageTest extends TestCase
8
{
9
    private function createMessage(): Message
10
    {
11
        return new Message();
12
    }
13
14
    public function testSetUp(): void
15
    {
16
        $message = $this->createMessage();
17
        $this->assertInstanceOf(\Swift_Message::class, $message->getSwiftMessage());
18
    }
19
20
    /**
21
     * @dataProvider dataProviderSubjects
22
     */
23
    public function testSubject(string $subject): void
24
    {
25
        $message = $this->createMessage()
26
            ->setSubject($subject);
27
        $this->assertSame($subject, $message->getSubject());
28
    }
29
30
    public function dataProviderSubjects(): array
31
    {
32
        return [
33
            ['foo'],
34
            ['bar'],
35
        ];
36
    }
37
38
    /**
39
     * @dataProvider dataProviderCharsets
40
     */
41
    public function testCharset(string $charset): void
42
    {
43
        $message = $this->createMessage()
44
            ->setCharset($charset);
45
        $this->assertSame($charset, $message->getCharset());
46
    }
47
48
    public function dataProviderCharsets(): array
49
    {
50
        return [
51
            ['utf-8'],
52
            ['iso-8859-2'],
53
        ];
54
    }
55
56
    /**
57
     * @dataProvider dataProviderFrom
58
     */
59
    public function testFrom($from, $expected): void
60
    {
61
        $message = $this->createMessage()
62
            ->setFrom($from);
63
        $this->assertEquals($expected, $message->getFrom());
64
    }
65
66
    public function dataProviderFrom(): array
67
    {
68
        return [
69
            [
70
                '[email protected]',
71
                ['[email protected]' => null]
72
            ],
73
            [
74
                ['[email protected]', '[email protected]'],
75
                ['[email protected]' => null, '[email protected]' => null],
76
            ],
77
            [
78
                ['[email protected]' => 'foo'],
79
                ['[email protected]' => 'foo']
80
            ],
81
            [
82
                ['[email protected]' => 'foo', '[email protected]' => 'bar'],
83
                ['[email protected]' => 'foo', '[email protected]' => 'bar']
84
            ],
85
        ];
86
    }
87
88
    /**
89
     * @dataProvider dataProviderRecipients
90
     */
91
    public function testTo($to, $expected): void
92
    {
93
        $message = $this->createMessage()
94
            ->setTo($to);
95
        $this->assertEquals($expected, $message->getTo());
96
    }
97
98
    /**
99
     * @dataProvider dataProviderRecipients
100
     */
101
    public function testCc($cc, $expected): void
102
    {
103
        $message = $this->createMessage()
104
            ->setCc($cc);
105
        $this->assertEquals($expected, $message->getCc());
106
    }
107
108
    /**
109
     * @dataProvider dataProviderRecipients
110
     */
111
    public function testBcc($bcc, $expected): void
112
    {
113
        $message = $this->createMessage()
114
            ->setBcc($bcc);
115
        $this->assertEquals($expected, $message->getBcc());
116
    }
117
118
    /**
119
     * @dataProvider dataProviderRecipients
120
     */
121
    public function testReplyTo($to, $expected): void
122
    {
123
        $message = $this->createMessage()
124
            ->setReplyTo($to);
125
        $this->assertEquals($expected, $message->getReplyTo());
126
    }
127
128
    /**
129
     * @dataProvider dataProviderRecipients
130
     */
131
    public function testReadReceiptTo($to, $expected): void
132
    {
133
        $message = $this->createMessage()
134
            ->setReadReceiptTo($to);
135
        $this->assertEquals($expected, $message->getReadReceiptTo());
136
    }
137
138
    public function dataProviderRecipients(): array
139
    {
140
        return [
141
            [
142
                '[email protected]',
143
                ['[email protected]' => null]
144
            ],
145
            [
146
                ['[email protected]', '[email protected]'],
147
                ['[email protected]' => null, '[email protected]' => null],
148
            ],
149
            [
150
                ['[email protected]' => 'foo'],
151
                ['[email protected]' => 'foo']
152
            ],
153
            [
154
                ['[email protected]' => 'foo', '[email protected]' => 'bar'],
155
                ['[email protected]' => 'foo', '[email protected]' => 'bar']
156
            ],
157
        ];
158
    }
159
160
    public function testReturnPath(): void
161
    {
162
        $address = '[email protected]';
163
        $message = $this->createMessage()->setReturnPath($address);
164
        $this->assertEquals($address, $message->getReturnPath());
165
    }
166
167
    /**
168
     * @dataProvider dataProviderPriorities
169
     */
170
    public function testPriority(int $priority): void
171
    {
172
        $message = $this->createMessage()->setPriority($priority);
173
        $this->assertEquals($priority, $message->getPriority());
174
    }
175
176
    public function dataProviderPriorities(): array
177
    {
178
        return [
179
            [\Swift_Mime_SimpleMessage::PRIORITY_HIGHEST],
180
            [\Swift_Mime_SimpleMessage::PRIORITY_HIGH],
181
            [\Swift_Mime_SimpleMessage::PRIORITY_NORMAL],
182
            [\Swift_Mime_SimpleMessage::PRIORITY_LOW],
183
            [\Swift_Mime_SimpleMessage::PRIORITY_LOWEST],
184
        ];
185
    }
186
187
    /**
188
     * @dataProvider dataProviderHeaders
189
     */
190
    public function testHeader(string $name, $value, $expected): void
191
    {
192
        $message = $this->createMessage();
193
        $this->assertEmpty($message->getHeader($name));
194
        $message->setHeader($name, $value);
195
        $this->assertEquals($expected, $message->getHeader($name));
196
    }
197
198
    public function dataProviderHeaders(): array
199
    {
200
        return [
201
            ['X-Foo', 'Bar', ['Bar']],
202
            ['X-Fuzz', ['Bar', 'Baz'], ['Bar', 'Baz']],
203
        ];
204
    }
205
206
    public function testTextBody(): void
207
    {
208
        $body = 'Dear foo';
209
        $message = $this->createMessage()
210
            ->setTextBody($body);
211
        $this->assertEquals($body, $message->getTextBody());
212
    }
213
214
    public function testHtmlBody(): void
215
    {
216
        $body = '<p>Dear foo</p>';
217
        $message = $this->createMessage()
218
            ->setHtmlBody($body);
219
        $this->assertEquals($body, $message->getHtmlBody());
220
    }
221
222
    public function testClone(): void
223
    {
224
        $m1 = new Message();
225
        $m1->setFrom('[email protected]');
226
        $m2 = clone $m1;
227
        $m1->setTo(['[email protected]' => 'user1']);
228
        $m2->setTo(['[email protected]' => 'user2']);
229
230
        $this->assertEquals(['[email protected]' => 'user1'], $m1->getTo());
231
        $this->assertEquals(['[email protected]' => 'user2'], $m2->getTo());
232
233
        $messageWithoutSwiftInitialized = new Message();
234
        $m2 = clone $messageWithoutSwiftInitialized; // should be no error during cloning
235
        $this->assertTrue($m2 instanceof Message);
236
    }
237
238
    public function testSetupHeaderShortcuts(): void
239
    {
240
        $charset = 'utf-16';
241
        $subject = 'Test Subject';
242
        $from = '[email protected]';
243
        $replyTo = '[email protected]';
244
        $to = '[email protected]';
245
        $cc = '[email protected]';
246
        $bcc = '[email protected]';
247
        $returnPath = '[email protected]';
248
        $readReceiptTo = '[email protected]';
249
250
        $messageString = $this->createMessage()
251
            ->setCharset($charset)
252
            ->setSubject($subject)
253
            ->setFrom($from)
254
            ->setReplyTo($replyTo)
255
            ->setTo($to)
256
            ->setCc($cc)
257
            ->setBcc($bcc)
258
            ->setReturnPath($returnPath)
259
            ->setPriority(2)
260
            ->setReadReceiptTo($readReceiptTo)
261
            ->toString();
262
263
        $this->assertStringContainsString('charset=' . $charset, $messageString, 'Incorrect charset!');
264
        $this->assertStringContainsString('Subject: ' . $subject, $messageString, 'Incorrect "Subject" header!');
265
        $this->assertStringContainsString('From: ' . $from, $messageString, 'Incorrect "From" header!');
266
        $this->assertStringContainsString('Reply-To: ' . $replyTo, $messageString, 'Incorrect "Reply-To" header!');
267
        $this->assertStringContainsString('To: ' . $to, $messageString, 'Incorrect "To" header!');
268
        $this->assertStringContainsString('Cc: ' . $cc, $messageString, 'Incorrect "Cc" header!');
269
        $this->assertStringContainsString('Bcc: ' . $bcc, $messageString, 'Incorrect "Bcc" header!');
270
        $this->assertStringContainsString("Return-Path: <{$returnPath}>", $messageString, 'Incorrect "Return-Path" header!');
271
        $this->assertStringContainsString('X-Priority: 2 (High)', $messageString, 'Incorrect "Priority" header!');
272
        $this->assertStringContainsString('Disposition-Notification-To: ' . $readReceiptTo, $messageString, 'Incorrect "Disposition-Notification-To" header!');
273
    }
274
275
    public function testSetupHeaders(): void
276
    {
277
        $messageString = $this->createMessage()
278
            ->addHeader('Some', 'foo')
279
            ->addHeader('Multiple', 'value1')
280
            ->addHeader('Multiple', 'value2')
281
            ->toString();
282
283
        $this->assertStringContainsString('Some: foo', $messageString, 'Unable to add header!');
284
        $this->assertStringContainsString('Multiple: value1', $messageString, 'First value of multiple header lost!');
285
        $this->assertStringContainsString('Multiple: value2', $messageString, 'Second value of multiple header lost!');
286
287
        $messageString = $this->createMessage()
288
            ->setHeader('Some', 'foo')
289
            ->setHeader('Some', 'override')
290
            ->setHeader('Multiple', ['value1', 'value2'])
291
            ->toString();
292
293
        $this->assertStringContainsString('Some: override', $messageString, 'Unable to set header!');
294
        $this->assertStringNotContainsString('Some: foo', $messageString, 'Unable to override header!');
295
        $this->assertStringContainsString('Multiple: value1', $messageString, 'First value of multiple header lost!');
296
        $this->assertStringContainsString('Multiple: value2', $messageString, 'Second value of multiple header lost!');
297
298
        $message = $this->createMessage();
299
        $message->setHeader('Some', 'foo');
300
        $this->assertEquals(['foo'], $message->getHeader('Some'));
301
        $message->setHeader('Multiple', ['value1', 'value2']);
302
        $this->assertEquals(['value1', 'value2'], $message->getHeader('Multiple'));
303
304
        $message = $this->createMessage()
305
            ->setHeaders([
306
                'Some' => 'foo',
307
                'Multiple' => ['value1', 'value2'],
308
            ]);
309
        $this->assertEquals(['foo'], $message->getHeader('Some'));
310
        $this->assertEquals(['value1', 'value2'], $message->getHeader('Multiple'));
311
    }
312
313
    public function testSerialize(): void
314
    {
315
        $message = $this->createMessage()
316
            ->setTo('[email protected]')
317
            ->setFrom('[email protected]')
318
            ->setSubject('Yii Swift Alternative Body Test')
319
            ->setTextBody('Yii Swift test plain text body');
320
321
        $serializedMessage = serialize($message);
322
        $this->assertNotEmpty($serializedMessage, 'Unable to serialize message!');
323
324
        $unserializedMessaage = unserialize($serializedMessage);
325
        $this->assertEquals($message, $unserializedMessaage, 'Unable to unserialize message!');
326
    }
327
328
    public function testSetBodyWithSameContentType()
329
    {
330
        $message = $this->createMessage();
331
        $message->setHtmlBody('body1');
332
        $message->setHtmlBody('body2');
333
        $this->assertEquals('body2', $message->getHtmlBody());
334
    }
335
336
    public function testAlternativeBodyCharset(): void
337
    {
338
        $message = $this->createMessage();
339
        $charset = 'windows-1251';
340
        $message->setCharset($charset);
341
342
        $message->setTextBody('some text');
343
        $message->setHtmlBody('some html');
344
        $content = $message->toString();
345
        $this->assertEquals(2, substr_count($content, $charset), 'Wrong charset for alternative body.');
346
347
        $message->setTextBody('some text override');
348
        $content = $message->toString();
349
        $this->assertEquals(2, substr_count($content, $charset), 'Wrong charset for alternative body override.');
350
    }
351
352
    public function testSendAlternativeBody()
353
    {
354
        $message = $this->createMessage()
355
            ->setTo('[email protected]')
356
            ->setFrom('[email protected]')
357
            ->setSubject('Yii Swift Alternative Body Test')
358
            ->setHtmlBody('<b>Yii Swift</b> test HTML body')
359
            ->setTextBody('Yii Swift test plain text body');
360
361
        $messageParts = $message->getSwiftMessage()->getChildren();
362
        $textPresent = false;
363
        $htmlPresent = false;
364
        foreach ($messageParts as $part) {
365
            if (!($part instanceof \Swift_Mime_Attachment)) {
366
                /* @var $part \Swift_Mime_MimePart */
367
                if ($part->getContentType() == 'text/plain') {
368
                    $textPresent = true;
369
                }
370
                if ($part->getContentType() == 'text/html') {
371
                    $htmlPresent = true;
372
                }
373
            }
374
        }
375
        $this->assertTrue($textPresent, 'No text!');
376
        $this->assertTrue($htmlPresent, 'No HTML!');
377
    }
378
379
    public function testEmbedContent(): void
380
    {
381
        $fileFullName = $this->createImageFile('embed_file.jpg', 'Embed Image File');
382
        $message = $this->createMessage();
383
384
        $fileName = basename($fileFullName);
385
        $contentType = 'image/jpeg';
386
        $fileContent = file_get_contents($fileFullName);
387
388
        $cid = $message->embedContent($fileContent, ['fileName' => $fileName, 'contentType' => $contentType]);
389
390
        $message->setTo('[email protected]');
391
        $message->setFrom('[email protected]');
392
        $message->setSubject('Yii Swift Embed File Test');
393
        $message->setHtmlBody('Embed image: <img src="' . $cid . '" alt="pic">');
394
395
        $attachment = $this->getAttachment($message);
396
        $this->assertTrue(is_object($attachment), 'No attachment found!');
397
        $this->assertEquals($fileName, $attachment->getFilename(), 'Invalid file name!');
398
        $this->assertEquals($contentType, $attachment->getContentType(), 'Invalid content type!');
399
    }
400
401
    public function testAttachFile(): void
402
    {
403
        $message = $this->createMessage();
404
405
        $message->setTo('[email protected]');
406
        $message->setFrom('[email protected]');
407
        $message->setSubject('Yii Swift Attach File Test');
408
        $message->setTextBody('Yii Swift Attach File Test body');
409
        $fileName = __FILE__;
410
        $options = [
411
            'fileName' => $fileName,
412
            'contentType' => 'application/x-php',
413
        ];
414
        $message->attach($fileName, $options);
415
416
        $attachment = $this->getAttachment($message);
417
        $this->assertTrue(is_object($attachment), 'No attachment found!');
418
        $this->assertStringContainsString($attachment->getFilename(), $options['fileName'], 'Invalid file name!');
419
        $this->assertEquals($options['contentType'], $attachment->getContentType(), 'Invalid content type!');
420
    }
421
422
    public function testAttachContent(): void
423
    {
424
        $message = $this->createMessage();
425
426
        $message->setTo('[email protected]');
427
        $message->setFrom('[email protected]');
428
        $message->setSubject('Yii Swift Create Attachment Test');
429
        $message->setTextBody('Yii Swift Create Attachment Test body');
430
        $fileName = 'test.txt';
431
        $fileContent = 'Test attachment content';
432
        $options = ['fileName' => $fileName, 'contentType' => 'text/plain'];
433
        $message->attachContent($fileContent, $options);
434
435
        $attachment = $this->getAttachment($message);
436
        $this->assertTrue(is_object($attachment), 'No attachment found!');
437
        $this->assertEquals($options['fileName'], $attachment->getFilename(), 'Invalid file name!');
438
        $this->assertEquals($options['contentType'], $attachment->getContentType(), 'Invalid content type!');
439
    }
440
441
    public function testEmbedFile(): void
442
    {
443
        $fileName = $this->createImageFile('embed_file.jpg', 'Embed Image File');
444
445
        $message = $this->createMessage();
446
447
        $options = ['fileName' => $fileName, 'contentType' => 'image/jpeg'];
448
        $cid = $message->embed($fileName, $options);
449
450
        $message->setTo('[email protected]');
451
        $message->setFrom('[email protected]');
452
        $message->setSubject('Yii Swift Embed File Test');
453
        $message->setHtmlBody('Embed image: <img src="' . $cid . '" alt="pic">');
454
455
        $attachment = $this->getAttachment($message);
456
        $this->assertTrue(is_object($attachment), 'No attachment found!');
457
        $this->assertStringContainsString($attachment->getFilename(), $fileName, 'Invalid file name!');
458
        $this->assertEquals($options['fileName'], $attachment->getFilename(), 'Invalid file name!');
459
        $this->assertEquals($options['contentType'], $attachment->getContentType(), 'Invalid content type!');
460
    }
461
462
    /**
463
     * @dataProvider dataProviderSigners
464
     */
465
    public function testAttachSigners(\Swift_Signer ... $signers): void
466
    {
467
        $message = $this->createMessage();
468
        $message->attachSigners($signers);
469
470
        $property = new \ReflectionProperty(\Swift_Message::class, 'headerSigners');
471
        $property->setAccessible(true);
472
        $headerSigners = $property->getValue($message->getSwiftMessage());
473
        $this->assertEquals($signers, $headerSigners);
474
    }
475
476
    private $privateKey = "-----BEGIN RSA PRIVATE KEY-----
477
MIIEpAIBAAKCAQEAyehiMTRxvfQz8nbQQAgL481QipVMF+E7ljWKHTQQSYfqktR+
478
zFYqX81vKeK9/2D6AiK5KJSBVdF7aURasppuDaxFJWrPvacd3IQCrGxsGkwwlWPO
479
ggB1WpOEKhVUZnGzdm96Fk23oHFKrEiQlSG0cB9P/wUKz57b8tsaPve5sKBG0Kww
480
9YIDRM0x4w3c9fupPz8H5p2HHn4uPbn+whJyALZHD1+CftIGOHq8AUH4w4Z7bjF4
481
DD4zibpgRn96BVaRIJjxZdlKq69v52j3v8O8SAqSkWmpDWiIsm85Gl00Loay6iiJ
482
XNy11y0sUysFeCSpb/9cRyxb6j0jEwQXrw0J/QIDAQABAoIBAQCFuRgXeKGAalVh
483
V5mTXwDo7hlSv5C3HCBH2svPjaTf3lnYx033bXYBH2Fpf1fQ5NyQP4kcPEbwnJ48
484
2N2s/qS2/4qIPpa6CA259+CBbAmo3R8sQf8KkN0okRzudlQAyXtPjINydCSS6ZXI
485
RwMjEkCcJdDomOFRIuiPjtdyLsXYGRAa95yjpTU0ri1mEJocX6tlchlgUsjwc2ml
486
rCTKLc6b3KtYNYUZ/Rg0HzWRIhkbQFIz7uS0t7gF3sqDOLcaoWIv2rmrpg5T0suA
487
e5Sz7nK2XBeaPi/AKNCVoXJiCJ6SU6A+6Q4T5Rvnt+uxGpLKiilb/fRpQaq1RFO9
488
k5BDPgftAoGBAPyYBPrTPYPYGosqzbFypNaWLOUnjkdFxlThpwvLOa7nzwVcsQ8V
489
EXDkELNYy/jOYJLsNhhZ+bGAwWdNV46pdurFKuzS4vb11RfZCc3BTM05IFUFrKir
490
YVgWw5AYKJLkUiACASEP55P8j2cKocCV5SdI0sGyU7W+3S1NbhBOlr0nAoGBAMyh
491
Y/Ki5wo3LX43l9F1I2HnKVJSj2XzpWTSYco8sUbS4yUBVk9qPBjIHhT+mK2k2FqD
492
bSWsu5tGVfaMlFbYxXnSBqjIQfHRLWWVmWMr5sLFk0aJyY1mjGh6BEhTp/Xs86/w
493
cdVlI1N5blxPy4VvoLmHIb/O1xqi64FV1gW7gD47AoGAErFlXPKZENLDVB08z67+
494
R+shM2wz+U5OmSWB6TuG70y0Y18ysz0J52LZYYxmu+j5+KWGc1LlSZ+PsIdmvWYJ
495
KOKihJgut7wFoxgqw5FUj7N0kxYyauET+SLmIhnHludStI+xabL1nlwIeMWupsPx
496
C3E2N6Ns0nxnfdzHEmneee0CgYA5kF0RcIoV8Ze2neTzY0Rk0iZpphf40iWAyz3/
497
KjukdMa5LjsddAEb54+u0EAa+Phz3eziYEkWUR71kG5aT/idYFvHNy513CYtIXxY
498
zYzI1dOsUC6GvIZbDZgO0Jm7MMEMiVM8eIsLfGlzRm82RkSsbDsuPf183L/rTj46
499
tphI6QKBgQDobarzJhVUdME4QKAlhJecKBO1xlVCXWbKGdRcJn0Gzq6iwZKdx64C
500
hQGpKaZBDDCHLk7dDzoKXF1udriW9EcImh09uIKGYYWS8poy8NUzmZ3fy/1o2C2O
501
U41eAdnQ3dDGzUNedIJkSh6Z0A4VMZIEOag9hPNYqQXZBQgfobvPKw==
502
-----END RSA PRIVATE KEY-----
503
";
504
505
    public function dataProviderSigners(): array
506
    {
507
        $domain = 'example.com';
508
        $selector = 'default';
509
510
        return [
511
            [new \Swift_Signers_DKIMSigner($this->privateKey, $domain, $selector)],
512
            [new \Swift_Signers_DKIMSigner($this->privateKey, $domain, $selector), new \Swift_Signers_DomainKeySigner($this->privateKey, $domain, $selector)],
513
        ];
514
    }
515
516
    /**
517
     * Creates image file with given text.
518
     * @param  string $fileName file name.
519
     * @param  string $text     text to be applied on image.
520
     * @return string image file full name.
521
     */
522
    protected function createImageFile(string $fileName = 'test.jpg', string $text = 'Test Image'): string
523
    {
524
        if (!function_exists('imagejpeg')) {
525
            $this->markTestSkipped('GD lib required.');
526
        }
527
        $fileFullName = $this->getTestFilePath() . DIRECTORY_SEPARATOR . $fileName;
528
        $image = \imagecreatetruecolor(120, 20);
529
        if ($image === false) {
530
            throw new \RuntimeExceptio('Unable create a new true color image');
531
        }
532
        $textColor = \imagecolorallocate($image, 233, 14, 91);
533
        \imagestring($image, 1, 5, 5, $text, $textColor);
534
        \imagejpeg($image, $fileFullName);
535
        \imagedestroy($image);
536
537
        return $fileFullName;
538
    }
539
540
    /**
541
     * Finds the attachment object in the message.
542
     * @param  Message                     $message message instance
543
     * @return null|\Swift_Mime_Attachment attachment instance.
544
     */
545
    protected function getAttachment(Message $message)
546
    {
547
        $messageParts = $message->getSwiftMessage()->getChildren();
548
        $attachment = null;
549
        foreach ($messageParts as $part) {
550
            if ($part instanceof \Swift_Mime_Attachment) {
551
                $attachment = $part;
552
                break;
553
            }
554
        }
555
556
        return $attachment;
557
    }
558
559
    /**
560
     * @return string test file path.
561
     *
562
     * @throws \RuntimeException
563
     */
564
    protected function getTestFilePath(): string
565
    {
566
        $dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR
567
            . str_replace('\\', '_', get_class($this)) . '_' . getmypid();
568
569
        if (!is_dir($dir) && mkdir($dir, 0777, true) === false) {
570
            throw new \RuntimeException('Unable to create temporary directory');
571
        }
572
573
        return $dir;
574
    }
575
}
576