Skip to content

Commit

Permalink
FormData posts and uploads (#151)
Browse files Browse the repository at this point in the history
* feature: post data with formdata
closes #99

* feature: use phpgt/http Response for FormData posts and uploads
closes #150

* tweak: import CURLFile
  • Loading branch information
g105b authored Jul 4, 2023
1 parent 95bd9f1 commit 44df571
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 9 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"ext-json": "*",
"phpgt/async": "^1.0",
"phpgt/promise": "^2.2.3",
"phpgt/http": "^1.2",
"phpgt/http": "^1.2.1",
"phpgt/curl": "^3.1.1",
"phpgt/json": "^1.2",
"phpgt/propfunc": "^1.0"
Expand Down
15 changes: 8 additions & 7 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions example/05-upload-file.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
require(implode(DIRECTORY_SEPARATOR, ["..", "vendor", "autoload.php"]));

use Gt\Fetch\Http;
use Gt\Http\FormData;
use Gt\Http\Response;
use Gt\Json\JsonObject;

$formData = new FormData();
$formData->set("upload", new SplFileObject(__FILE__));

$http = new Http();
$http->fetch("https://postman-echo.com/post", [
"method" => "POST",
"headers" => [
"Content-type" => "multipart/form-data"
],
"body" => $formData,
])
->then(function(Response $response) {
if(!$response->ok) {
throw new RuntimeException("Error uploading file to Postman Echo.");
}
return $response->json();
})
->then(function(JsonObject $json) {
foreach($json->asArray()["files"] as $fileName => $data) {
echo $fileName . " - " . strlen($data) . " bytes", PHP_EOL;
}
})
->catch(function(Throwable $error) {
echo "An error occurred: ", $error->getMessage();
});

$http->wait();
die("done waiting");
15 changes: 14 additions & 1 deletion src/CurlOptBuilder.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?php
namespace Gt\Fetch;

use CURLFile;
use Gt\Http\File;
use Gt\Http\FormData;
use Gt\Http\RequestMethod;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
Expand Down Expand Up @@ -87,7 +90,17 @@ protected function setHeaders(array $headers):void {
* add to your request: this can be a string, associative array
* (representing form data) or binary object.
*/
protected function setBody(string|array $body):void {
protected function setBody(string|array|FormData $body):void {
if($body instanceof FormData) {
$formData = $body;
$body = [];
foreach($formData as $key => $value) {
if($value instanceof File) {
$value = new CURLFile($value->name);
}
$body[$key] = $value;
}
}
$this->curlOptArray[CURLOPT_POSTFIELDS] = $body;
}

Expand Down

0 comments on commit 44df571

Please sign in to comment.