8000 [Mime] Allow url as a path in the DataPart::fromPath · symfony/symfony@12bf8cb · GitHub
[go: up one dir, main page]

Skip to content

Commit 12bf8cb

Browse files
committed
[Mime] Allow url as a path in the DataPart::fromPath
1 parent 03bccf1 commit 12bf8cb

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Symfony/Component/Mime/Part/DataPart.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,20 @@ public static function fromPath(string $path, string $name = null, string $conte
6161
$contentType = self::$mimeTypes->getMimeTypes($ext)[0] ?? 'application/octet-stream';
6262
}
6363

64-
if (!is_file($path) || !is_readable($path)) {
64+
if ((is_file($path) && !is_readable($path)) || is_dir($path)) {
6565
throw new InvalidArgumentException(sprintf('Path "%s" is not readable.', $path));
6666
}
6767

6868
if (false === $handle = @fopen($path, 'r', false)) {
6969
throw new InvalidArgumentException(sprintf('Unable to open path "%s".', $path));
7070
}
71+
72+
if (!is_file($path)) {
73+
$cache = fopen('php://temp', 'r+');
74+
stream_copy_to_stream($handle, $cache);
75+
$handle = $cache;
76+
}
77+
7178
$p = new self($handle, $name ?: basename($path), $contentType);
7279
$p->handle = $handle;
7380

src/Symfony/Component/Mime/Tests/Part/DataPartTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,30 @@ public function testFromPathWithNotAFile()
134134
DataPart::fromPath(__DIR__.'/../Fixtures/mimetypes/');
135135
}
136136

137+
/**
138+
* @group network
139+
*/
140+
public function testFromPathWithUrl()
141+
{
142+
if (!\in_array('https', stream_get_wrappers())) {
143+
$this->markTestSkipped('"https" stream wrapper is not enabled.');
144+
}
145+
146+
$p = DataPart::fromPath($file = 'https://symfony.com/images/common/logo/logo_symfony_header.png');
147+
$content = file_get_contents($file);
148+
$this->assertEquals($content, $p->getBody());
149+
$maxLineLength = 76;
150+
$this->assertEquals(substr(base64_encode($content), 0, $maxLineLength), substr($p->bodyToString(), 0, $maxLineLength));
151+
$this->assertEquals(substr(base64_encode($content), 0, $maxLineLength), substr(implode('', iterator_to_array($p->bodyToIterable())), 0, $maxLineLength));
152+
$this->assertEquals('image', $p->getMediaType());
153+
$this->assertEquals('png', $p->getMediaSubType());
154+
$this->assertEquals(new Headers(
155+
new ParameterizedHeader('Content-Type', 'image/png', ['name' => 'logo_symfony_header.png']),
156+
new UnstructuredHeader('Content-Transfer-Encoding', 'base64'),
157+
new ParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'logo_symfony_header.png', 'filename' => 'logo_symfony_header.png'])
158+
), $p->getPreparedHeaders());
159+
}
160+
137161
public function testHasContentId()
138162
{
139163
$p = new DataPart('content');

0 commit comments

Comments
 (0)
0