Skip to content

Commit d8dc034

Browse files
MatsNyholm
authored andcommitted
Added support for multipart stream created from uri streams (#27)
* Added support for multipart uri streams by ensuring content from non-seekable streams is not fetched using string casting. Added testSupportURIResources phpUnit test validating the multipart stream created from an uri resource. Changed composer dev requirement zendframework/zend-diactoros for guzzlehttp/psr7 due to the fact that zend-diactoros DiactorosStreamFactory's createStream function runs a rewind which throws an exception if stream is not seekable. Removed dependency on Zend\Diactoros\Stream in unit tests. * Reverted to Diactoros dependency. * refactoring: improved naming in line with other tests. * when building the stream changed from toString via string casting to explicitly calling __toString() for clarity as suggested by @Nyholm
1 parent 5e02c79 commit d8dc034

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/MultipartStreamBuilder.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,14 @@ public function build()
9595
$this->getHeaders($data['headers'])."\r\n";
9696

9797
// Convert the stream to string
98-
$streams .= (string) $data['contents'];
98+
/* @var $contentStream StreamInterface */
99+
$contentStream = $data['contents'];
100+
if ($contentStream->isSeekable()) {
101+
$streams .= $contentStream->__toString();
102+
} else {
103+
$streams .= $contentStream->getContents();
104+
}
105+
99106
$streams .= "\r\n";
100107
}
101108

tests/FunctionTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,22 @@ public function testSupportResources()
3333
$this->assertTrue(false !== strpos($multipartStream, 'Content-Type: image/png'));
3434
}
3535

36+
public function testSupportURIResources()
37+
{
38+
$url = 'https://raw.githubusercontent.com/php-http/multipart-stream-builder/master/tests/Resources/httplug.png';
39+
$resource = fopen($url, 'r');
40+
41+
$builder = new MultipartStreamBuilder();
42+
$builder->addResource('image', $resource);
43+
$multipartStream = (string) $builder->build();
44+
45+
$this->assertTrue(false !== strpos($multipartStream, 'Content-Disposition: form-data; name="image"; filename="httplug.png"'));
46+
$this->assertTrue(false !== strpos($multipartStream, 'Content-Type: image/png'));
47+
48+
$urlContents = file_get_contents($url);
49+
$this->assertContains($urlContents, $multipartStream);
50+
}
51+
3652
public function testResourceFilenameIsNotLocaleAware()
3753
{
3854
// Get current locale

0 commit comments

Comments
 (0)