Skip to content

Commit

Permalink
Better File Upload Support
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelJ2324 committed Jul 14, 2017
1 parent a4bc1d8 commit 067a29f
Showing 1 changed file with 42 additions and 10 deletions.
52 changes: 42 additions & 10 deletions src/Request/AbstractRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -285,32 +285,45 @@ public function setBody($body)
/**
* @inheritdoc
*/
public function addFile($bodyKey,$fullFilePath){
public function addFile($bodyKey,$fullFilePath,$mimeType='',$uploadName=''){
if (file_exists($fullFilePath) && is_readable($fullFilePath)){
$File = $this->getLegacyFileHandle($fullFilePath);
$File = $this->getLegacyFileHandle($fullFilePath,$mimeType,$uploadName);
if (version_compare(PHP_VERSION, '5.5.0') >= 0){
$File = $this->getFileHandle($fullFilePath);
$File = $this->getFileHandle($fullFilePath,$mimeType,$uploadName);
}
$this->body[$bodyKey] = $File;
$this->upload = TRUE;
$this->setUpload(TRUE);
}
return $this;
}

/**
* @param $fullFilePath
* @param $mimeType
* @param $uploadName
* @return string
*/
private function getLegacyFileHandle($fullFilePath){
return '@'.$fullFilePath;
private function getLegacyFileHandle($fullFilePath,$mimeType='',$uploadName='')
{
$fileHandle = '@'.$fullFilePath;
if ($mimeType !== ''){
$fileHandle .= ';type='.$mimeType;
}
if ($uploadName !== ''){
$fileHandle .= ';filename='.$uploadName;
}
return $fileHandle;
}

/**
* @param $fullFilePath
* @param $mimeType
* @param $uploadName
* @return \CURLFile
*/
private function getFileHandle($fullFilePath){
return new \CURLFile($fullFilePath);
private function getFileHandle($fullFilePath,$mimeType='',$uploadName='')
{
return new \CURLFile($fullFilePath,$mimeType,$uploadName);
}

/**
Expand Down Expand Up @@ -399,6 +412,24 @@ public function send()
return $this;
}

/**
* Set the upload property which allows us to track when Body is uploading a file
* @param bool $upload
* @return $this
*/
public function setUpload($upload){
$this->upload = (bool)$upload;
return $this;
}

/**
* Check the upload property on the Request Object
* @return bool
*/
public function getUpload(){
return $this->upload;
}

/**
* @inheritdoc
*/
Expand Down Expand Up @@ -480,9 +511,10 @@ protected function configureHeaders(array $headers){
* @return bool
*/
protected function configureBody($body){
$upload = $this->getUpload();
switch ($this->method) {
case self::HTTP_GET:
if (!$this->upload){
if (!$upload){
if (is_array($body) || is_object($body)){
$queryParams = http_build_query($body);
} else {
Expand All @@ -499,7 +531,7 @@ protected function configureBody($body){
break;
}
default:
if ($this->upload){
if ($upload){
$this->addHeader('Content-Type','multipart/form-data');
}
return $this->addCurlOption(CURLOPT_POSTFIELDS, $body);
Expand Down

0 comments on commit 067a29f

Please sign in to comment.