Skip to content

Commit a9a3328

Browse files
author
Maz
committed
Accepts nested array in multipart option field value
1 parent a70f5c9 commit a9a3328

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/MultipartStream.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@ private function addElement(AppendStream $stream, array $element): void
9191
}
9292
}
9393

94+
if (is_array($element['contents'])) {
95+
$prepare = function ($contents, $key, $root = null) use ($stream, &$values, &$prepare) {
96+
$fieldName = $root ? sprintf('%s[%s]', $root, $key) : $key;
97+
98+
if (is_array($contents)) {
99+
array_walk($contents, $prepare, $fieldName);
100+
return;
101+
}
102+
103+
$this->addElement($stream, ['name' => $fieldName, 'contents' => Utils::streamFor($contents)]);
104+
};
105+
106+
array_walk($element['contents'], $prepare, $element['name']);
107+
108+
return;
109+
}
110+
94111
$element['contents'] = Utils::streamFor($element['contents']);
95112

96113
if (empty($element['filename'])) {

tests/MultipartStreamTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,35 @@ public function testSerializesNonStringFields(): void
127127
self::assertSame($expected, (string) $b);
128128
}
129129

130+
public function testExpandNestedArrayFields(): void
131+
{
132+
$b = new MultipartStream([
133+
[
134+
'name' => 'foo',
135+
'contents' => [
136+
['key' => 'bar'],
137+
['key' => 'baz']
138+
]
139+
]
140+
], 'boundary');
141+
142+
$expected = \implode('', [
143+
"--boundary\r\n",
144+
"Content-Disposition: form-data; name=\"foo[0][key]\"\r\n",
145+
"Content-Length: 3\r\n",
146+
"\r\n",
147+
"bar\r\n",
148+
"--boundary\r\n",
149+
"Content-Disposition: form-data; name=\"foo[1][key]\"\r\n",
150+
"Content-Length: 3\r\n",
151+
"\r\n",
152+
"baz\r\n",
153+
"--boundary--\r\n",
154+
]);
155+
156+
self::assertSame($expected, (string) $b);
157+
}
158+
130159
public function testSerializesFiles(): void
131160
{
132161
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [

0 commit comments

Comments
 (0)