Skip to content

Commit dfeaf94

Browse files
committed
Fix repeated attachment content reads
1 parent ac8a4d0 commit dfeaf94

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

src/Attachment.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,10 @@ public function contentDisposition(): string
117117
*/
118118
public function contents(): string
119119
{
120+
if ($this->contentStream->isSeekable()) {
121+
$this->contentStream->rewind();
122+
}
123+
120124
return $this->contentStream->getContents();
121125
}
122126

tests/Unit/AttachmentTest.php

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,44 @@
11
<?php
22

33
use DirectoryTree\ImapEngine\Attachment;
4-
use GuzzleHttp\Psr7\LazyOpenStream;
4+
use GuzzleHttp\Psr7\Utils;
55

66
test('extension', function () {
7-
$stream = new LazyOpenStream('test.jpg', 'r');
7+
$stream = Utils::streamFor('');
88

99
$ext = (new Attachment('test.jpg', null, 'image/jpeg', 'attachment', $stream))->extension();
1010

1111
expect($ext)->toBe('jpg');
1212
});
1313

1414
test('extension with content type', function () {
15-
$stream = new LazyOpenStream('test', 'r');
15+
$stream = Utils::streamFor('');
1616

1717
$ext = (new Attachment('test', null, 'image/jpeg', 'attachment', $stream))->extension();
1818

1919
expect($ext)->toBe('jpg');
2020
});
21+
22+
test('contents can be read multiple times', function () {
23+
$stream = Utils::streamFor('Hello World!');
24+
25+
$attachment = new Attachment('test.txt', null, 'text/plain', 'attachment', $stream);
26+
27+
expect($attachment->contents())->toBe('Hello World!');
28+
expect($attachment->contents())->toBe('Hello World!');
29+
});
30+
31+
test('save writes contents after reading contents', function () {
32+
$stream = Utils::streamFor('Hello World!');
33+
34+
$attachment = new Attachment('test.txt', null, 'text/plain', 'attachment', $stream);
35+
36+
$path = tempnam(sys_get_temp_dir(), 'imap-engine-attachment-');
37+
38+
$attachment->contents();
39+
$attachment->save($path);
40+
41+
expect(file_get_contents($path))->toBe('Hello World!');
42+
43+
unlink($path);
44+
});

0 commit comments

Comments
 (0)