Add attachment from memory (#158)

This commit is contained in:
Wim Verstuyf 2016-09-06 13:05:50 +02:00 committed by Tobias Nyholm
parent 18804d491f
commit 5d04bc63a7
3 changed files with 72 additions and 9 deletions

View File

@ -261,8 +261,17 @@ class RestClient
protected function prepareFile($fieldName, $filePath, $fileIndex=0)
{
$filename = null;
$resource = null;
if (is_array($filePath) && isset($filePath['fileContent'])) {
// File from memory
$filename = $filePath['filename'];
$resource = fopen('php://temp', 'r+');
fwrite($resource, $filePath['fileContent']);
rewind($resource);
} else {
// Backward compatibility code
if (is_array($filePath)) {
if (is_array($filePath) && isset($filePath['filePath'])) {
$filename = $filePath['remoteName'];
$filePath = $filePath['filePath'];
}
@ -272,12 +281,15 @@ class RestClient
$filePath = substr($filePath, 1);
}
$resource = fopen($filePath, 'r');
}
// Add index for multiple file support
$fieldName .= '[' . $fileIndex . ']';
return [
'name' => $fieldName,
'contents' => fopen($filePath, 'r'),
'contents' => $resource,
'filename' => $filename,
];
}

View File

@ -0,0 +1,50 @@
<?php
namespace Mailgun\Tests\Functional;
/**
* Add attachment with file from memory
*
* @author Wim Verstuyf <wim.verstuyf@codelicious.be>
*/
class FileFromMemoryTest extends \PHPUnit_Framework_TestCase
{
public function testAddFileFromMemory()
{
$fileValidator = function($files) {
// Get only the attachments so the properties can be converted to a format we like
$attachments = array_filter($files, function($f) {
return strpos($f['name'], 'attachment') !== false;
});
// Convert resources to strings
$attachments = array_map(function($f) {
return [
'name' => $f['name'],
'contents' => fread($f['contents'], 50),
'filename' => $f['filename'],
];
}, $attachments);
$this->assertContains(['name'=>'attachment[0]', 'contents'=>'File content', 'filename' => 'file1.txt'], $attachments);
$this->assertContains(['name'=>'attachment[1]', 'contents'=>'File content 2', 'filename' => 'file2.txt'], $attachments);
$this->assertContains(['name'=>'attachment[2]', 'contents'=>'Contents of a text file', 'filename' => 'text_file.txt'], $attachments);
};
$attachments = [
['filename' => 'file1.txt', 'fileContent' => "File content"],
['filename' => 'file2.txt', 'fileContent' => "File content 2"],
['filePath' => "./tests/TestAssets/text_file.txt", 'remoteName' => 'text_file.txt']
];
$mailgun = MockedMailgun::create($this, 'POST', 'domain/messages', [], $fileValidator);
$mailgun->sendMessage('domain', array(
'from' => 'bob@example.com',
'to' => 'alice@example.com',
'subject' => 'Foo',
'text' => 'Bar'), array(
'attachment' => $attachments
));
}
}

View File

@ -0,0 +1 @@
Contents of a text file