feature/add-attachments #2

Manually merged
Thifaine merged 12 commits from feature/add-attachments into master 2020-06-09 16:20:07 +02:00
2 changed files with 59 additions and 4 deletions

View File

@ -5,6 +5,8 @@ namespace Bluescale\Mail;
use Bluescale\Mail\BluescaleMailTemplate;
use GuzzleHttp\Client;
use Psr\Http\Message\StreamInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class BluescaleMailApi
{
@ -43,7 +45,6 @@ class BluescaleMailApi
if (!empty($recipient['address']))
if ($notifiable_email == $recipient['address'])
$notifiable_recipient = true;
if (!$notifiable_recipient)
$template->recipients[] = [
@ -51,10 +52,33 @@ class BluescaleMailApi
];
}
$multipart_form = [];
foreach ($template as $key => $value) { // Formatting whole template to pass in 'multipart' form
if (!is_array($value)) {
$multipart_form[] = ['name' => $key, 'contents' => $value];
continue;
}
foreach ($value as $multiKey => $multiValue) {
$multiName = $key . '[' .$multiKey . ']' . (is_array($multiValue) ? '[' . key($multiValue) . ']' : '' );
$data = ['name' => $multiName];
if ($key === "attachments") {
$data['contents'] = file_get_contents($multiValue['path']);
$data['filename'] = $multiValue['filename'];
} else {
$data['contents'] = (is_array($multiValue) ? reset($multiValue) : $multiValue);
}
$multipart_form[] = $data;
}
}
try {
return $client->request('post', $url, [
'form_params' => $template,
'headers' => [
return $client->request('post', $url, [
'multipart' => $multipart_form,
'headers' => [
'Authorization' => 'Bearer ' . $this->api_key,
'Accept' => 'application/json'
]

View File

@ -26,6 +26,13 @@ class BluescaleMailTemplate implements \JsonSerializable
public $recipients = [];
/**
* The attachments for the message
*
* @var array
*/
public $attachments = [];
/**
* The reply address for the message
*
* @var array
@ -137,6 +144,29 @@ class BluescaleMailTemplate implements \JsonSerializable
}
/**
* @param array $attachments
* @return BluescaleMailTemplate
*/
public function attachments(array $attachments): BluescaleMailTemplate
{
foreach ($attachments as $attachment) {
$this->addAttachment($attachment['path'] ?? $attachment['file'], $attachment['filename'] ?? null);
}
return $this;
}
public function addAttachment($file, $filename = null)
{
$file = is_object($file) && method_exists($file, 'getRealPath') ? $file->getRealPath() : $file;
$this->attachments[] = [
'path' => $file,
'filename' => $filename ?? basename($file)
];
}
/**
* @param string $key
* @param string $value
* @return BluescaleMailTemplate
@ -159,6 +189,7 @@ class BluescaleMailTemplate implements \JsonSerializable
'sender' => $this->sender,
'replyTo' => $this->replyTo,
'recipients' => $this->recipients,
'attachments' => $this->attachments,
'parameters' => $this->parameters,
];
}