Skip to content

Commit

Permalink
Enable file uploads
Browse files Browse the repository at this point in the history
If the $data array contains an item with key of 'attachments', the request will change to a multipart file upload instead of a json upload. The 'attachments' item is expected to be a stream from fopen, or an array of streams.
  • Loading branch information
OneHatRepo authored Apr 4, 2020
1 parent 9247ef4 commit 174c5f3
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,40 @@ public function __construct($apiKey, $domain)
*/
public function request($method, $endpoint, array $data = null, array $query = null)
{
$options = ['json' => $data];

if (isset($data['attachments'])) {
// Has file attachments, so we can't use the json property.
// Instead, we have to use the "multipart" property
$attachments = $data['attachments'];
unset($data['attachments']);

if (!is_array($attachments)) {
$attachments = [$attachments];
}

$multiparts = [];
foreach($attachments as $attachment) {
$multiparts[] = [
'name' => 'attachments[]',
'contents' => $attachment, // $attachment is a resource from fopen('/path/to/file', 'r')
];
}
foreach($data as $key => $value) {
$multiparts[] = [
'name' => $key,
'contents' => $value,
];
}

$options = [
'multipart' => $multiparts,
];
} else {
// normal method
$options = [
'json' => $data,
];
}

if (isset($query)) {
$options['query'] = $query;
Expand Down

0 comments on commit 174c5f3

Please sign in to comment.