Skip to content

Commit 44df571

Browse files
author
Greg Bowler
authored
FormData posts and uploads (#151)
* feature: post data with formdata closes #99 * feature: use phpgt/http Response for FormData posts and uploads closes #150 * tweak: import CURLFile
1 parent 95bd9f1 commit 44df571

File tree

4 files changed

+59
-9
lines changed

4 files changed

+59
-9
lines changed

composer.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"ext-json": "*",
1111
"phpgt/async": "^1.0",
1212
"phpgt/promise": "^2.2.3",
13-
"phpgt/http": "^1.2",
13+
"phpgt/http": "^1.2.1",
1414
"phpgt/curl": "^3.1.1",
1515
"phpgt/json": "^1.2",
1616
"phpgt/propfunc": "^1.0"

composer.lock

+8-7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/05-upload-file.php

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
require(implode(DIRECTORY_SEPARATOR, ["..", "vendor", "autoload.php"]));
3+
4+
use Gt\Fetch\Http;
5+
use Gt\Http\FormData;
6+
use Gt\Http\Response;
7+
use Gt\Json\JsonObject;
8+
9+
$formData = new FormData();
10+
$formData->set("upload", new SplFileObject(__FILE__));
11+
12+
$http = new Http();
13+
$http->fetch("https://postman-echo.com/post", [
14+
"method" => "POST",
15+
"headers" => [
16+
"Content-type" => "multipart/form-data"
17+
],
18+
"body" => $formData,
19+
])
20+
->then(function(Response $response) {
21+
if(!$response->ok) {
22+
throw new RuntimeException("Error uploading file to Postman Echo.");
23+
}
24+
return $response->json();
25+
})
26+
->then(function(JsonObject $json) {
27+
foreach($json->asArray()["files"] as $fileName => $data) {
28+
echo $fileName . " - " . strlen($data) . " bytes", PHP_EOL;
29+
}
30+
})
31+
->catch(function(Throwable $error) {
32+
echo "An error occurred: ", $error->getMessage();
33+
});
34+
35+
$http->wait();
36+
die("done waiting");

src/CurlOptBuilder.php

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
<?php
22
namespace Gt\Fetch;
33

4+
use CURLFile;
5+
use Gt\Http\File;
6+
use Gt\Http\FormData;
47
use Gt\Http\RequestMethod;
58
use Psr\Http\Message\RequestInterface;
69
use Psr\Http\Message\UriInterface;
@@ -87,7 +90,17 @@ protected function setHeaders(array $headers):void {
8790
* add to your request: this can be a string, associative array
8891
* (representing form data) or binary object.
8992
*/
90-
protected function setBody(string|array $body):void {
93+
protected function setBody(string|array|FormData $body):void {
94+
if($body instanceof FormData) {
95+
$formData = $body;
96+
$body = [];
97+
foreach($formData as $key => $value) {
98+
if($value instanceof File) {
99+
$value = new CURLFile($value->name);
100+
}
101+
$body[$key] = $value;
102+
}
103+
}
91104
$this->curlOptArray[CURLOPT_POSTFIELDS] = $body;
92105
}
93106

0 commit comments

Comments
 (0)