1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-24 18:13:00 +01:00

Merge remote-tracking branch 'larowlan/multipart-forms' into fix-multipart-nested

This commit is contained in:
Michael Dowling 2014-06-04 14:30:46 -07:00
commit 7ad15b806f
2 changed files with 41 additions and 12 deletions

View File

@ -245,6 +245,31 @@ class PostBody implements PostBodyInterface
return $this->aggregator;
}
/**
* Flatten nested fields array into name => value pairs.
*
* @param array $fields Fields to flatten.
* @param string $keyPrefix Key prefix (start with '')
*
* @return array
*/
private static function flattenFields(array $fields, $keyPrefix = '')
{
$result = [];
foreach ($fields as $key => $value) {
if ($keyPrefix) {
$key = "{$keyPrefix}[{$key}]";
}
if (is_array($value)) {
$result += self::flattenFields($value, $key);
} else {
$result[$key] = $value;
}
}
return $result;
}
/**
* Creates a multipart/form-data body stream
*
@ -252,18 +277,7 @@ class PostBody implements PostBodyInterface
*/
private function createMultipart()
{
$fields = $this->fields;
$query = (new Query())
->setEncodingType(false)
->setAggregator($this->getAggregator());
// Account for fields with an array value
foreach ($fields as $name => &$field) {
if (is_array($field)) {
$field = (string) $query->replace([$name => $field]);
}
}
$fields = self::flattenFields($this->fields);
return new MultipartBody($fields, $this->files);
}

View File

@ -64,6 +64,21 @@ class PostBodyTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($m->hasHeader('Content-Length'));
}
public function testMultipartWithNestedFields()
{
$b = new PostBody();
$b->setField('foo', ['bar' => 'baz']);
$b->forceMultipartUpload(true);
$this->assertEquals(['foo' => ['bar' => 'baz']], $b->getFields());
$m = new Request('POST', '/');
$b->applyRequestHeaders($m);
$this->assertContains('multipart/form-data', (string) $m->getHeader('Content-Type'));
$this->assertTrue($m->hasHeader('Content-Length'));
$contents = $b->getContents();
$this->assertContains('name="foo[bar]"', $contents);
$this->assertNotContains('name="foo"', $contents);
}
public function testCountProvidesFieldsAndFiles()
{
$b = new PostBody();